Figure out size of UILabel based on String in Swift

后端 未结 11 1516
执笔经年
执笔经年 2020-11-22 13:35

I am trying to calculate the height of a UILabel based on different String lengths.

func calculateContentHeight() -> CGFloat{
    var maxLabelSize: CGSize         


        
11条回答
  •  独厮守ぢ
    2020-11-22 14:28

    For multiline text this answer is not working correctly. You can build a different String extension by using UILabel

    extension String {
    func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let label =  UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.text = self
        label.font = font
        label.sizeToFit()
    
        return label.frame.height
     }
    }
    

    The UILabel gets a fixed width and the .numberOfLines is set to 0. By adding the text and calling .sizeToFit() it automatically adjusts to the correct height.

    Code is written in Swift 3

提交回复
热议问题