I have one image that I want to add as background image to uibutton. I want to stretch the image to fit button width. User will enter the title for button at runtime.So depending on width of text entered by user , it will strech the image. Beyond a certain width of the button , the button will not stretch further but instead the text will get truncated. Here is my code
CGSize suggestedSize = [self.strButtonTitle sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSLog(@"Widht:- %f",suggestedSize.width);
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
customButton.frame = CGRectMake(50, 200, 75, 40);
CGRect frame = customButton.frame;
frame.size.width = suggestedSize.width;
if (frame.size.width > 75) {
frame.size.width = 75;
customButton.frame = frame;
}
else {
frame.size.width +=5;
customButton.frame = frame;
}
NSLog(@"Custom button width:- %f",customButton.frame.size.width);
UIImage *buttonImageNormal = [UIImage imageNamed:BUTTON_IMAGE];
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[customButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
[customButton setTitle:self.strButtonTitle forState:UIControlStateNormal];
[customButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:customButton];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = barButton;
[barButton release];
My problem is , button width doesn’t increase according to text entered by user.
If user enter ppppp, width doesn’t increase upto 75 instead it is showing “pp…p”
Any knid of help is highly appreciated. Thanks.
The problem is in measuring the width of string. You are measuring the width of string by below way.
Here you are using systemFont with size as FONT_SIZE.
However you are not setting the same font to your customButton textlabel. It can be done by below way.
Hope it will help.