Tips for calculating the height and width of UILabel single line and multi-line text in IOS development
I 've been studying IOS for a while, and it is especially painful to calculate the height of this text content. This is simply not comparable to Android. Android does not have to worry about calculating the width and height, all of them help you implement it internally. Well, YY is over now, and you have to solve the problem of such a pain point.
First, let's look at the single-line text problem: for a single-line text, it is relatively simple to calculate the CGSize. Here the code is directly listed as follows:
NSString * content = @ "Welcome to Beijing ";
CGSize size = [content sizeWithAttributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 14]}];
14 indicates the font size. You can specify the font size as needed.
Finally, let's look at the display of multi-line text:
First set numberOfLines of UILabel to 0, and then use-(CGRect) boundingRectWithSize :( CGSize) size options :( NSStringDrawingOptions) options attributes :( NSDictionary *) attributes context :( NSStringDrawingContext *) the specific code is as follows:
UILabel * titleLabel = [UILabel new];
TitleLabel. font = [UIFont systemFontOfSize: 14];
NSString * titleContent = @ ", you are welcome to contact our marketing consultant through the following methods to discuss your problems in the marketing promotion work, the marketing consultant will provide you with consulting services free of charge. ";
TitleLabel. text = titleContent;
TitleLabel. numberOfLines = 0; // multi-row display, computing height
TitleLabel. textColor = [UIColor lightGrayColor];
CGSize titleSize = [titleContent usage: CGSizeMake (kScreen_Width, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin attributes :@{ NSFontAttributeName: [UIFont systemFontOfSize: 14]} context: nil]. size;
TitleLabel. size = titleSize;
TitleLabel. x = 0;
TitleLabel. y = 0;
[Self. view addSubview: titleLabel];
The final steps are as follows: