How to give dynamic height to UILabel programmatically in Swift?

前端 未结 8 1626
夕颜
夕颜 2021-01-02 00:11

I have taken UIlabel which are generated dynamically using for loop, each type diff text is assign in label, I want to give UILabel size dynamically depending on text.

8条回答
  •  醉梦人生
    2021-01-02 00:59

    The Swift 4.1 extension method to calculate label height:

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

    Refer: Adjust UILabel height to text

提交回复
热议问题