很多UILabel的使用場景下,需要根據(jù)字符串大小來計(jì)算UILabel的大小,以保證UILabel的美觀:
使用NSString的方法:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
即可計(jì)算字符串的大小。
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];
// 根據(jù)字符串大小計(jì)算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