UIButton to be resized
I am using a UIButton in my application. This button title is displayed dynamically as per the user choice. Now i have to resize the button width as per the title content. I am calculating the string length and assigning it to button's width.
the button is resized as per title but the problem is as follows, 1. If at first the title with large content is shown and after that if a title with a small content is shown means the button is overwritten it doesn't remove the previously constructed v开发者_如何学Pythonalue. 2. it looks as if one button is overlapped on the another.
Assuming, you have your attribute button in your class
-(void)changeTitleButtonWithValue:(NSString *)value
{
//get the value length (- (CGSize)sizeWithFont:(UIFont *)font)
size = [value sizeWithFont:yourFont];
self.button.frame = CGRectMake(x, y, size.width,size.height);
[self.button setTitle:value forState:UIControlStateNormal];
[self.button setTitle:value forState:UIControlStateHighlighted];
}
Edit : you have many ways to get your button
- Your create it from Interface Builder
- Add it as an Outlet
- Set it a tag and getIt with UIButton *myButton = (UIButton *)[self.view viewForTag:YOURTAG];
- You create it from code
- Instance attribute
- Same thing with tag but when you create it : myButton.tag = YOURTAG;
To me, it sounds like you are not changing the width of the button but you are adding another button. Are you adding the buttons in code? If you do, could you post the code?
In general, if you want to add another button, it would be best, to give it a tag and remove the view with that tag (i.e. the old button) from the superview before adding the new.
This should look something like this (from the top of my head):
UIButton * button = [[[UIButton alloc] init] autorelease];
button.tag = 100;
/* ...set up the button the way you would normally do... */
// remove old button
[[targetView viewWithTag: 100] removeFromSuperview];
// add new button
[targetView addSubview: button];
The tag is an arbitrary integer used to identify a view. It would be best to #define
your used tags in a central place.
精彩评论