2017-01-19 7 views
1

私は、セル内のattributedStringの高さと等しいtableViewCellの高さを設定しようとしています。しかし、私が何をしても、正しいサイズを持っていないようです。これは私がこれまで試したものです帰属文字列の高さを計算する

cellHeight

//Convert description to NSAttributedString and get height 
//width is equal to screen width - right and left offset 
//at the end add the bottom and height offset to the cell height 
return detailPetViewModel!.description 
       .lineSpacing(spacing: 4) 
       .heightWithConstrainedWidth(width: Sizes.screenWidth - 40) + 10 
細胞サブクラス

//Customize descLabel 
descLabel.font = FontFamily.Avenir.Regular.font(size: 16) 
descLabel.textColor = UIColor(named: .SecondaryTextColor) 

//Multiple lines 
descLabel.numberOfLines = 0 
descLabel.lineBreakMode = .byWordWrapping 
descLabel.sizeToFit() 

カスタマイズdescLabel linespacing延長

extension String { 
    func lineSpacing(spacing: CGFloat) -> NSAttributedString { 

     let paragraphStyle = NSMutableParagraphStyle() 
     paragraphStyle.lineSpacing = spacing 

     let attributedString = NSMutableAttributedString(string: self) 
     attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length)) 
     return attributedString 
    } 
} 

高拡張

extension NSAttributedString { 
    func heightWithConstrainedWidth(width: CGFloat) -> CGFloat { 
     let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) 
     let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) 

     return boundingBox.height 
    } 

} 
+0

:このように使用

extension NSAttributedString { func height(containerWidth: CGFloat) -> CGFloat { let rect = self.boundingRect(with: CGSize.init(width: containerWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) return ceil(rect.size.height) } func width(containerHeight: CGFloat) -> CGFloat { let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: containerHeight), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) return ceil(rect.size.width) } } 

? – holex

答えて

0

これは私が使用する拡張機能です。フォントや行の高さに関する情報を属性文字列として渡す必要はありません。あなたの代わりに、動的セルの高さの利点を使用していない理由を

let height = detailPetViewModel!.description.height(containerWidth: Sizes.screenWidth - 40 + 10) 
+0

2つのピリオド(detailPetViewModel!.description..height)を1つ(detailPetViewModel!.description.height)にする必要があった場合は、構文を細かく修正する必要があります –

関連する問題