I am trying to add a bunch of UIButton to a horizontal UIScrollView using the following code, however I am not seeing anything and all I see is just a white UIScrollBar. Why is this? I am pretty sure that I messed up something as before it was just working just fine.
self.category = [[NSArray alloc]initWithObjects:#"ALL", #"FOOD",#"NIGHT LIFE",#"ARTS & ENTERTAINMENT",#"SPORT", #"SHOP", #"COLLEGE & UNIVERSITY", #"TRAVEL SPOT", nil];
self.scrollView.delegate = self;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = YES;
int xOffset = 0;
for(int index=0; index < [self.category count]; index++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.titleLabel setTextAlignment:UITextAlignmentCenter];
[button setBackgroundImage:[UIImage imageNamed:#"CategoryTab.png"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTag:index];
[button addTarget:self action:#selector(pressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[self.category objectAtIndex:index] forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont fontWithName:#"bebas" size:15.0]];
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [[self.category objectAtIndex:index] sizeWithFont:[UIFont fontWithName:#"ArialMT" size:15.0]
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
[button setFrame: CGRectMake(xOffset, 0, expectedLabelSize.width + 30, 38)];
[self.scrollView addSubview:button];
xOffset += expectedLabelSize.width + 30;
[button release];
}
self.scrollView.contentSize = CGSizeMake(xOffset, 38);
A few possible causes :
The UIButton is released once too often. It's created autoreleased, then added to the scrollview, then released, which effectively means it will be dealloc'd when the autorelease pool ends. I'm surprised this does not crash, actually. Are you using Automatic Reference Counting?
is self.scrollview correctly initialized? If it's nil, it will simply fail silently.
is the "bebas" font really loaded and available? Custom font loading isn't that trivial on iOS.
Also :
You're not using the actual button font to measure the label size. ("bebas" vs "ArialMT")
you probably have a leak on line 1. That NSArray would better be autoreleased ( using[NSArray arrayWithObjects:...]).
autoresizingMask is not a BOOL value, it's an OR combination of flags.
Related
I had an application in which i am setting the content size of the scroll view dynamically according to the number of buttons which i am creating from an array.like this `
for(int i =0;i<[sarray count];i++)
{
NSMutableDictionary *dicttable=[sarray objectAtIndex:i];
NSString *head=[dicttable objectForKey:#"cat"];
btn= [UIButton buttonWithType:UIButtonTypeCustom];
int j=i+1;
btn.frame = CGRectMake((j-1)*87,0,87, 44);
[btn setBackgroundImage:[UIImage imageNamed:#"bar.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:#"bar_hvr.png"] forState:UIControlStateSelected];
btn.backgroundColor = [UIColor clearColor];
btn.titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14];
btn.titleLabel.textColor = [UIColor whiteColor];
[btn setTitle:head forState:UIControlStateNormal];
btn.tag = i;
[btn setShowsTouchWhenHighlighted:YES];
[Scroller addSubview:btn];
[btn addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
if(btn.tag==0)
{
sendActionsForControlEvents:UIControlEventTouchUpInside];
}
else
{
btn.selected=NO;
}
}
}
[Scroller setContentSize:CGSizeMake([sarray count]*85, 44)];
`
but here the problem is after the last button also the scroll view scrolls .it need not to be happend,i need the scrolling ends with last button on the view,can anybody help me on this
set scrollview bounces to NO
scrollView.bounces = NO;
yes as you said it looses the smoothness. But no other choice. If you found any sol please update the answer.
hey i am sending you complete example to make button dynamicay and seting the content size scrollview on number of count ,i had just given u one example code u have to set the size of frame of button as u requried
UIScrollView *scroll_View=[[UIScrollView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:scroll_View];
int y=0;
for(int i =1;i<10;i++)
{
// NSMutableDictionary *dicttable=[sarray objectAtIndex:i];
// NSString *head=[dicttable objectForKey:#"cat"];
UIButton* btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(y,89,100, 50);
[btn setBackgroundImage:[UIImage imageNamed:#"bar.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:#"bar_hvr.png"] forState:UIControlStateSelected];
btn.backgroundColor = [UIColor clearColor];
btn.titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14];
NSString *str=[NSString stringWithFormat:#"%d",i];
btn.titleLabel.textColor = [UIColor whiteColor];
[btn setTitle:str forState:UIControlStateNormal];
btn.tag = i;
[btn setShowsTouchWhenHighlighted:YES];
[scroll_View addSubview:btn];
[btn addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
y=110*i;
}
[scroll_View setContentSize:CGSizeMake(y, 400)];
enjoy coding
You just declare one yMargin variable of type CGFloat and initialize it with some required value as 0. Now every time whenever you are adding a new subview vertically do y+=lbl.frame.size.height;
Now setContentSize:CGSizeMake([sarray count]*85, y margin+someRequiredMargin)];
(someRequiredMargin - you want to add below )
I am developing application like Instagram.
I have code for cellForRowAtIndexPath, every time it creates object for unbutton and it is autorelease. this button display username and it may be 1,2,3,4,5,.. total like users. there for i create UIButton on depend on like cout.
I am not using ARC.
but it crash sometimes (Not everyTime) when setColour.
I enabled NSZombie and it keeps saying:
[UIDeviceRGBColor set]: message sent to deallocated instance 0x21b526f0
UIButton *btnLikeUserName = [[[UIButton alloc] init] autorelease];
[btnLikeUserName.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
if (posx + size.width > 280) {
posy = posy + 22;
posx = 18;
btnLikeUserName.frame = CGRectMake(posx,posy,size.width,size.height);
posx = posx + size.width + 5;
}
else {
btnLikeUserName.frame = CGRectMake(posx,posy,size.width,size.height);
posx = posx + size.width + 5;
}
btnLikeUserName.tag = shareObjU.userId;
[btnLikeUserName setTitle:text forState:UIControlStateNormal];
[btnLikeUserName setTitleColor:[UIColor colorWithRed:50/255.0 green:79/255.0 blue:133/255.0 alpha:1.0] forState:UIControlStateNormal]; ////Hear is crash
[btnLikeUserName addTarget:self action:#selector(btnLikeUserNameClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.viewLikeComment addSubview:btnLikeUserName];
i also see following link
UISwitch setThumbTintColor causing crash (iOS 6 only)?
1 out of 4 colors return errors
iOS App crashes when using colorWithRed:green:blue:alpha
and other .. but all says for global Objct. not local object. how can i solved it.
Thank You
try this code...
[btnLikeUserName setTitleColor:[UIColor colorWithRed:((float) 50 / 255.0f)
green:((float) 79 / 255.0f)
blue:((float) 133 / 255.0f)
alpha:1.0f] forState:UIControlStateNormal];
OR Also you can set UIColor like bellow.
[btnLikeUserName setTitleColor:[UIColor colorWithRed:50.0f/255.0f green:79.0f/255.0f blue:133.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
And Here you Add UIButtons in every cell then try to define like bellow not alloc and autorelease everytime .....
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
*UPDATE:*See the example which i add in my every cell with multiple button like GridView
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = rect;
button.tag = imageIndex;
[button addTarget:self action:#selector(btnTemp_Clicked:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:[arrTime objectAtIndex:imageIndex] forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
//[button setTitleColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"circle03.jpg"]] forState:UIControlStateNormal ];
[button setTitleColor:[UIColor colorWithRed:50.0f/255.0f green:79.0f/255.0f blue:133.0f/255.0f alpha:1.0] forState:UIControlStateHighlighted ];
[button setNeedsDisplay];
[gridCell.contentView addSubview:button];
I need to draw dynamic images on UIScrollView for this i use, MKHorizion menu (A subclass of Scroll view). Now i add Subview images on scrollview. Loop worked perfectly for adding subview on scrollview. Now in My parent class I need to touch scroll view for updated data. If i didn't touch then it is not showing updated data. Below is code
-(void) reloadData
{
[self deleteAlliTem];
self.itemCount = [dataSource numberOfImagesForMenu:self];
self.backgroundColor = [dataSource backgroundColorForImage:self];
UIFont *buttonFont = [UIFont boldSystemFontOfSize:15];
int buttonPadding = 0;
int tag = kButtonBaseTag;
int xPos = kLeftOffset;
for(int i = 0 ; i < self.itemCount; i ++)
{
NSLog(#"*************************************************************");
NSMutableDictionary *dictData=[dataSource horizMenuImage:self dictForItmeAtIndex:i];
NSString *title=[dictData valueForKey:#"name"] ? [dictData valueForKey:#"name"] : #"";
UIImage* imageItem= [UIImage imageWithData:[Base64 decode:[dictData valueForKey:#"img"]]];
int buttonWidth = 95;
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setTitle:title forState:UIControlStateNormal];
customButton.titleLabel.font = buttonFont;
[customButton setBackgroundImage:[UIImage imageNamed:#"addFriendStrip.png"] forState:UIControlStateNormal];
[customButton setBackgroundImage:[UIImage imageNamed:#"addFriendStrip.png"] forState:UIControlStateSelected];
customButton.tag = tag++;
[customButton addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
customButton.frame = CGRectMake(xPos, 70, buttonWidth + buttonPadding, 25);
customButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
customButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
customButton.titleEdgeInsets =UIEdgeInsetsMake(0, 10,0, 0);
customButton.titleLabel.font = [UIFont fontWithName:#"Overlock-Bold" size:16];
[customButton setTitleColor:[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1] forState:UIControlStateNormal];
[customButton setTitleColor:[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1] forState:UIControlStateSelected];
UIImageView* itemImageView = [[UIImageView alloc] initWithImage:imageItem];
itemImageView.tag = 200 + customButton.tag;
[itemImageView setFrame:CGRectMake(xPos, 0, buttonWidth + buttonPadding, 95)];
[self addSubview:itemImageView];
[itemImageView release];
itemImageView = nil;
[self addSubview:customButton];
xPos += buttonWidth;
xPos += buttonPadding;
if (i != self.itemCount-1){
xPos += 2.5; //5; // Richa
}
}
self.contentSize = CGSizeMake(xPos, 95);
NSLog(#"############################################################################ - %d",[[self subviews] count]);
[self scrollRectToVisible:CGRectMake(1, 0, self.frame.size.width, self.frame.size.height) animated:YES];
}
Please Help me to sort out this. Why do i needed to touch scroll view ? Do i need to override other methods ?
Did you check it is on main thread ? may be you are using GCD Queue thats why it is not updating till touch.
just try to bring your scrollview on top.I am not getting your question correctly ,but it may help.
Let me know if it is working or not..!!!
Happy Coding.!!!!
I am trying to create number of buttons on view programatically and for that I need array, so can I add button object in NSMutableArray?
Yes you can do that see the following code
// Create buttons for the sliding menu. For simplicity I create 5 standard buttons.
NSMutableArray *buttonArray = [[NSMutableArray alloc] init];
for(NSInteger i = 0; i < [self.slideMenuArray count]; i++)
{
// Rounded rect is nice
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *title=[slideMenuArray objectAtIndex:i];
[btn setFrame:CGRectMake(0.0f, 4.0f, 90.0f, 20.0f)];
[btn setTitle:[NSString stringWithString:title] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[[btn titleLabel] setFont:[UIFont systemFontOfSize:12]];
[btn addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIImage *backgroundView;
if(i==0)
backgroundView= [UIImage imageNamed:#"btnclk.png"];
else
backgroundView= [UIImage imageNamed:#"btn.png"];
[btn setBackgroundImage:backgroundView forState:UIControlStateNormal];
[buttonArray addObject:btn];
}
You can retrieve the added button objects like this-
for(int i = 0; i < [buttonArray count]; i++)
{
UIButton *btn = [buttonArray objectAtIndex:i];
// Move the buttons position in the x-demension (horizontal).
CGRect btnRect = btn.frame;
btnRect.origin.x = totalButtonWidth;
[btn setFrame:btnRect];
}
sure you can, and remember that when you do, every button or other object will be retained bu the array and released when you remove it from the array...
Yes, NSMutableArray can hold any objects
Everything about this UIButton renders great except the text that's supposed to be on it. NSLog demonstrates that the text is in the right place. What gives?
UIButton *newTagButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[newTagButton addTarget:self action:#selector(showNewTagField) forControlEvents:UIControlEventTouchUpInside];
newTagButton.titleLabel.text = #"+ New Tag";
NSLog(#"Just set button label to %#", newTagButton.titleLabel.text);
newTagButton.titleLabel.font = [UIFont systemFontOfSize:17];
newTagButton.titleLabel.textColor = [UIColor redColor];
CGSize addtextsize = [newTagButton.titleLabel.text sizeWithFont:[UIFont systemFontOfSize:17]];
CGSize buttonsize = { (addtextsize.width + 20), (addtextsize.height * 1.2) };
newTagButton.frame = CGRectMake(x, y, buttonsize.width, buttonsize.height);
[self.mainView addSubview:newTagButton];
There are a set of APIs on UIButton that should be used to change those properties.
The titleLabel can and will be changed by the UIButton internally.
[button setTitle:title forState:state];
[button setTitleColor:color forState:state];
[button setTitleShadowColor:color forState:state];
You should always set these properties through these methods (when available) rather than touching the titleLabel directly. For fonts you can change it on the titleLabel directly since they don't provide a method on UIButton.