How to calculate TextView height base on text

前端 未结 6 2066
無奈伤痛
無奈伤痛 2021-01-05 02:43

I am using the code below for calculate the height of text, then set this height for UILabel and UITextView

CGSize targetSize = CGS         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 03:07

    Swift 5

    A classic hack I've used to do this is create a function that takes the String as a parameter. Within the function it generates a label with the width required, infinite number of lines, and a height of "too much". Then apply sizeToFit() on the label and return the height of the frame.

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

    The returned height can be applied to a UITextField height anchor. Though I do recommend calculating the width dynamically based on screen size, but that's up to you.

提交回复
热议问题