How to adjust the height of a textview to his content in SWIFT?

前端 未结 7 747
无人及你
无人及你 2020-12-07 23:05

In my view controller, I have an UITextView. This textview is filled with a string. The string can be short or long. Depending on the length of the string, the height of the

7条回答
  •  隐瞒了意图╮
    2020-12-07 23:51

    In Swift 3.0, where tvHeightConstraint is the height constraint of the subject TextView (if using for multiple textviews, would add it to the function inputs):

    func textViewDidChange(textView: UITextView) {
    
            let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
            if size.height != tvHeightConstraint.constant && size.height > textView.frame.size.height{
                tvHeightConstraint.constant = size.height
                textView.setContentOffset(CGPoint.zero, animated: false)
            }
        }
    

    H/T to @cmi and @Pablo Ruan

提交回复
热议问题