iOS 根据字符串的实际大小来计算UILabel的size

释放双眼,带上耳机,听听看~!

根据字符串大小来计算UILabel的size

很多UILabel的使用场景下,需要根据字符串大小来计算UILabel的大小,以保证UILabel的美观:
使用NSString的方法:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode

即可计算字符串的大小。

NSString *text = @"The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind. The Foundation framework includes the root object class, classes representing basic data types such as strings and byte arrays, collection classes for storing other objects, classes representing system information such as dates, and classes representing communication ports. See Cocoa Objective-C Hierarchy for Foundation for a list of those classes that make up the Foundation framework.";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 50)];
label.backgroundColor = [UIColor grayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
label.text = text;
[self.view addSubview:label];
// 根据字符串大小计算label的大小
CGSize size = [label.text sizeWithFont:[UIFont boldSystemFontOfSize:17.0f] constrainedToSize:CGSizeMake(self.view.frame.size.width, 300) lineBreakMode:NSLineBreakByWordWrapping];
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, size.height);

Demo

Demo地址: DemoUILabel

人已赞赏
iOS文章

iOS开发Objective-C 的switch语句中不能初始化对象

2020-4-4 5:46:48

iOS文章

iOS如何隐藏APP的statusBar

2020-4-4 7:01:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索