UILabel 根据text的内容来调整大小
生活随笔
收集整理的這篇文章主要介紹了
UILabel 根据text的内容来调整大小
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有時候,在UILabel的text過長的時候,我們需要讓label進行自適應大小,之前我們必須要獲得這個UILabel的size,這便是根據text的內容和性質(字體,行間距等決定的)。? ? 在ios7中,使用boundingRectWithRect方法來獲得CGSize: ? ? //文字的字體
NSDictionary *attribute = @{NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:15.0f]};//將text轉化為NSMutableAttributedString類型
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_titleLabel.text attributes:attribute];//設置行間距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:6.0f];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_titleLabel.text length])];//獲得UILabel的size,其中,296和93是size的限定值
CGSize DateSize = [attributedString boundingRectWithSize:CGSizeMake(296, 93) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;//如果UILabel的寬度太寬的話
if (DateSize.width > 518.0f/2)
{ _titleLabel.size = CGSizeMake(296.0f, DateSize.height);_titleLabel.textAlignment = NSTextAlignmentLeft;_titleLabel.lineBreakMode = NSLineBreakByCharWrapping;_titleLabel.numberOfLines = 0; //不限定行數,自動換行_titleLabel.attributedText = attributedString;
}
?
轉載于:https://www.cnblogs.com/rambot/p/3864263.html
總結
以上是生活随笔為你收集整理的UILabel 根据text的内容来调整大小的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 添加用户(过火绒)
- 下一篇: MaxtoCode!!国人开发的DotN