How to give dynamic height to UILabel programmatically in Swift?

前端 未结 8 1628
夕颜
夕颜 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:54
    let label = UILabel()
    label.backgroundColor = UIColor.greenColor()
    label.text = "Hello,world.\n Just a test."
    let font = UIFont.systemFontOfSize(17.0)
    label.font = font
    label.numberOfLines = 0;
    let text = label.text! as NSString
    let size = text.sizeWithAttributes([NSFontAttributeName:font])
    label.frame = CGRectMake(0, 0, size.width, size.height)
    

    You can use Auto Layout in code. See Auto Layout Guide

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题