给定所需的宽度和字体,我如何找到UILabel的高度?

时间:2016-05-06 19:31:37

标签: ios swift

func calculateHeightOfLabel(text: String, width: CGFloat, font: UIFont){
    //how can I find the height of a UILabel with these properties ?
}

UILabel可能有超过1行,此功能应考虑到这一点。

我想创建一个可以找到高度的全局辅助函数(就像它被添加到视图中一样)

2 个答案:

答案 0 :(得分:0)

这是我使用的方法

func getSize(text: String, labelfont fontType: UIFont, width labelwidth: Float) -> CGSize {
text = "\(text)"
var font1: UIFont = fontType
var attributedText: NSAttributedString = NSAttributedString(string: text, attributes: [NSFontAttributeName: font1])
var rect: CGRect = attributedText.boundingRectWithSize(CGRect()
    rect.labelwidth
    rect.CGFLOAT_MAX, options: .UsesLineFragmentOrigin, context: nil)
var size: CGSize = rect.size
return size

}

答案 1 :(得分:0)

夫特

 func sizeWithAttributes(_ attrs: [String : AnyObject]?) ->
     CGSize

目标-C

 - (CGSize)sizeWithAttributes:(NSDictionary<NSString *, id> * nullable)attributes

示例:

func calculateHeightOfLabel(text: String, width: CGFloat, font: UIFont) {
       return text.sizeWithAttributes([NSFontAttributeName: font]).height
}