简体   繁体   中英

Calculate height and number of lines of the label

I have a text that is shown in a UILabel . However, this text have several line spaces as shown below. Now, I want to calculate the height of this label, considering the newline, Bold-text and font size. Since this text can not be placed in a Single line in the label, there might be several lines that we must determine at runtime. Based on this height I want to increase the y cordinate of my UILabel so the UILabel will always be stuck to the bottom of the screen. (Only the height will increase (upwards))

How can I solve this?

NSAttributedString *linespace = [[NSAttributedString alloc] initWithString: @"\n"];

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:@"Mathews is a " attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:40]}];  

NSAttributedString*    attributed = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"Bad guy"] attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:40]}];


[mutableString appendAttributedString: linespace];

[mutableString appendAttributedString: attributed];

[mutableString appendAttributedString: linespace];

You can get height by

CGRect rectCountry = [mutableString boundingRectWithSize:(CGSize){@“YOUR WIDTH”, CGFLOAT_MAX}
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                     context:nil];
CGSize sizeCountry = rectCountry.size;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM