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

發佈了117 篇原創文章 · 獲贊 18 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章