How to give dynamic height to UILabel programmatically in Swift?

前端 未结 8 1693
夕颜
夕颜 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:51

    let label:UILabel = UILabel(frame: CGRectMake(x, y, width, height))
    label.numberOfLines = 4
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    let font = UIFont(name: "Helvetica", size: 20.0)
    label.font = font
    label.text = "Whatever you want the text enter here"
    label.sizeToFit()
    

    If you want to set numberOfLines according to the content of text,give your maximum lines.That is very important here.

提交回复
热议问题