iOS UILabel自訂行間距時擷取高度,iosuilabel

來源:互聯網
上載者:User

iOS UILabel自訂行間距時擷取高度,iosuilabel

本文介紹一下自訂行間距的UILabel的高度如何擷取,需要藉助一下開源的UILabel控制項:TTTAttributedLabel

附 https://github.com/TTTAttributedLabel/TTTAttributedLabel 

下載後,添加到工程裡面,匯入標頭檔

 #import "TTTAttributedLabel.h"

直接上代碼

NSString *str = @"UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度,UILabel自訂行間距時擷取高度.";        //建立tttLabel    TTTAttributedLabel *tttLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(30, 55, 300, 100)];    tttLabel.lineBreakMode = NSLineBreakByCharWrapping;    tttLabel.lineSpacing = 6;//設定行間距    tttLabel.font = [UIFont systemFontOfSize:12];    tttLabel.numberOfLines = 0; //設定行數為0    [tttLabel setText:str];    tttLabel.textAlignment = NSTextAlignmentLeft;    tttLabel.backgroundColor = [UIColor redColor];    [self.view addSubview:tttLabel];        //擷取tttLabel的高度    //先通過NSMutableAttributedString設定和上面tttLabel一樣的屬性,例如行間距,字型    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:str];    //自訂str和TTTAttributedLabel一樣的行間距    NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];    [paragrapStyle setLineSpacing:6];    //設定行間距    [attrString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, str.length)];    //設定字型    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, str.length)];        //得到自訂行間距的UILabel的高度    CGFloat height = [TTTAttributedLabel sizeThatFitsAttributedString:attrString withConstraints:CGSizeMake(300, MAXFLOAT) limitedToNumberOfLines:0].height;        //重新改變tttLabel的frame高度    CGRect rect = tttLabel.frame;    rect.size.height = height;    tttLabel.frame = rect;

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.