Size of label changes after being set, depending on string
I am facing an issue in getting the correct frame for two different strings. I am running two strings through the below code:
UILabel *myLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
myLabel.lineBreakMode = UILineBreakModeWordWrap;
myLabel.numberOfLines = 2;
myLabel.textAlignment = UITextAlignmentCenter;
myLabel.font = [UIFont boldSystemFontOfSize:11];
myLabel.text = @"About Stores"
myLabel.text = @"About Rivers"
CGSize myLabelSize = CGSizeMake(70,28);
[myLabel sizeWithFont:myString.font // <-- One of two strings
constrainedToSize:aLabelSize
lineBreakMode:UILineBreakModeWordWrap];
Result for myString1
=> Width: 70, Height: 28
myString2
=> Width: 70, Height开发者_如何学Python: 14
Why there is a difference here?
Issues I see:
1
NSString has no font property. You might want to replace "myString.font" with UILabel.font where the UILabel is to be replaced by the instance of UILabel you plan to use to display the string.
2
sizeWithFont is supposed to return a CGSize that you store in an instance of CGSize.
Seems like you're not very clear on using this. I've posted an answer on how to correctly use sizeWithFont. You should check that out here : Place two UILabels side by side left and right without knowing string length of text in left label
By the way, that's why you see a difference in the heights... I think a garbage value is being passed in as the font size argument. If you hardcode the font size argument, you'll see consistent results.
just replace the code n give a try.....i don kno if it works jus check :)
[myLabel sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:11]
constrainedToSize:myLabelSize lineBreakMode:UILineBreakModeWordWrap];
and also ";" is missing in label`
myLabel.text = @"About Stores"; myLabel.text = @"About Rivers";`
regards..
There's a difference because the system font is Helvetica, which is a variable-sized font. The text in myString1 is maginally wider than the text in myString2, so the string needs to wrap to a second line in order to fit. Since you specified 2 lines max and UILineBreakModeWordWrap, that's what you get. If you want it to fit in one line, make myLabelSize a little wider or else use a smaller font size.
精彩评论