iOS-根據(jù)字符串的實(shí)際大小來計(jì)算UILabel的size

很多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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,320評論 4 61
  • 當(dāng)你覺得生活停止不前的時(shí)候,你最向往什么? 當(dāng)你覺得工作枯燥無味的時(shí)候,你會(huì)去做什么? 當(dāng)你知道生命無法永生的時(shí)候...
    別鬧淡定閱讀 404評論 0 0
  • 2016年5月、6月這兩個(gè)月的時(shí)間里,除了工作,我做了我覺得很有意義的5件事:讀書、文案學(xué)習(xí)、跑步、早起、參...
    哇飛起的青蛙閱讀 584評論 0 0
  • 不知道是不是因?yàn)閭€(gè)性或者從小成長的環(huán)境,特別不喜歡做聚光燈下面的那個(gè)。 比如,英語課,幾乎保持沉默了一年,一是自己...
    指尖明媚閱讀 255評論 0 0

友情鏈接更多精彩內(nèi)容