iOS 8 開始可以配合 AutoLayout 自動估算文本的高度,但是當 Cell 比較復雜的時候,還會需要手動去計算。首先聲明一個樣式
var TextStyle : [String : NSObject] { get { let paraStyle = NSMutableParagraphStyle() paraStyle.minimumLineHeight = 17.3 paraStyle.lineSpacing = 0 paraStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping paraStyle.paragraphSpacing = 0 paraStyle.paragraphSpacingBefore = 0 return [NSForegroundColorAttributeName: UIColor.blackColor(), NSKernAttributeName: CGFloat(0.5), NSFontAttributeName: UIFont.systemFontOfSize(15.0), NSParagraphStyleAttributeName: paraStyle ] }}
如果你的文本里含有很多特殊字符,例如顏文字,通過 NSKernAttributeName 設置字間距可以算出更寬松的結果。
以 UILabel 為例,設置其 attributedText
label.attributedText = NSAttributedString(string: "Hello World", attributes: TextStyle))
再利用 boundingRectWithSize 這個方法來計算其約束后的高度,傳入一個 width 為寬度約束,然后利用我們聲明的樣式來計算高度。
func sizeHeightWithText(attrString: NSString, width: CGFloat, textAttributes: [NSObject : AnyObject]) -> CGSize { var rect = attrString.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: .UsesLineFragmentOrigin | .UsesFontLeading, attributes: textAttributes, context: nil) return CGSize(width: rect.width, height: rect.height)}
如果你使用的是 UITextView,那么還需要對 UITextView 做一些處理來去掉他的邊距。
textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsetsZero
新聞熱點
疑難解答