func estimatedLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
let size = CGSize(width: width, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: font]
let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
return rectangleHeight
}
使用方法:
// 1. get the text from the label
guard let theLabelsText = myLabel.text else { return }
// 2. get the width of the view the label is in for example a cell
// Here I'm just stating that the cell is the same exact width of whatever the collection's width is which is usually based on the width of the view that collectionView is in
let widthOfCell = self.collectionView.frame.width
// 3. get the font that your using for the label. For this example the label's font is UIFont.systemFont(ofSize: 17)
let theLabelsFont = UIFont.systemFont(ofSize: 17)
// 4. Plug the 3 values from above into the function
let totalLabelHeight = estimatedLabelHeight(text: theLabelsText, width: widthOfCell, font: theLabelsFont)
// 5. Print out the label's height with decimal values eg. 95.46875
print(totalLabelHeight)
// 6. as @slashburn suggested in the comments, use the ceil() function to round out the totalLabelHeight
let ceilHeight = ceil(totalLabelHeight)
// 7. Print out the ceilHeight rounded off eg. 95.0
print(ceilHeight)
5条答案
按热度按时间b5lpy0ml1#
Swift 4带扩展
clj7thdc2#
很简单,只要打电话
3hvapo4f3#
针对Swift 3更新
u4dcyp6a4#
Swift 5 ioS 13.2经100%测试,当UI标签****行数= 0时为最佳解决方案
注意,结果是四舍五入的。如果不需要,只需删除ceil()。
如果要获取高度-〉为情节提要提供UILabel宽度
如果要获取宽度-〉为UILabel给予故事板高度
c9qzyr3d5#
@iajmeri43的答案已为Swift 5更新
使用方法: