有時候,在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; }
?