How to give dynamic height to UILabel programmatically in Swift?

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

    NSString(string: "hello this is a string").boundingRect(
            with: CGSize(width: width, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: self],
            context: nil).size
    

    Use this method to get determine the size for you string. Put maximum height and maximum width in CGSize(widhth,height) and it will return CGSize object containing height and width. Use it according with your scenario

提交回复
热议问题