How to get the height of a UILabel in Swift?

前端 未结 5 968
误落风尘
误落风尘 2020-12-17 15:21

I am a beginner in Swift and I am trying to get the height of a label. The label has multiple lines of text. I want to know the total height it occupies on the screen.

5条回答
  •  渐次进展
    2020-12-17 16:08

    Swift 4 with extension

    extension UILabel{
    
    public var requiredHeight: CGFloat {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text
        label.attributedText = attributedText
        label.sizeToFit()
        return label.frame.height
      }
    }
    

提交回复
热议问题