Bangalore
Bangalore

Reputation: 1580

UIButton not showing complete title?

Iam dynamically generating UIButton and when i set title name without space its showing correctly. For eg:

NSString *myString=[[array valueForKey:@"optionName"] objectAtIndex:i];
NSLog(@"%@",myString); // myString=SampleTitle
[button setTitle:myString forState:UIControlStateNormal];

and when i set name with space its auto trimming UIButton title. For eg:

NSString *myString=[[array valueForKey:@"optionName"] objectAtIndex:i];
NSLog(@"%@",myString); // myString=SampleTitle Test
[button setTitle:myString forState:UIControlStateNormal];

Its showing like this

enter image description here

HOw can i remove this trimming part? i need to show all characters properly.

and my UIButton size is calculating based on title

[button setTitle:myString forState:UIControlStateNormal];
        CGSize stringsize = [@"Prolonged inspiration" sizeWithFont:[UIFont systemFontOfSize:14]];
        //or whatever font you're using
        [button setFrame:CGRectMake(x,y,stringsize.width+30,stringsize.height+20)];

Upvotes: 0

Views: 363

Answers (2)

Sreedeepkesav M S
Sreedeepkesav M S

Reputation: 1173

Try this for iOS versions above iOS 7.0

CGSize textSize = { widthValue, CGFLOAT_MAX };            
CGRect frame = [text boundingRectWithSize:textSize
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:@{ NSFontAttributeName:font }
                                      context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);

Upvotes: 0

rmaddy
rmaddy

Reputation: 318804

The most likely cause of your issue is that you calculate the size of the text using a font that is likely different from the button's font. Base your calculation on the button's font as well as the button's text.

CGSize stringsize = [myString sizeWithFont:button.titleLabel.font];

As a side note, the sizeWithFont: method was deprecated back in iOS 7.0. Unless you are also supporting iOS 6, you should replace that method with the proper replacement.

Upvotes: 1

Related Questions