Search code examples
iosswifttextviewresizewidth

Resize TextView Heigh AND Width according to text - Swift


I'm trying to auto resize a UITextView in a TableView Custom Cell using the below function in my TableViewController. It works perfectly: it resize my TextView heigh according to the text length BUT I cannot find any help on how to adjust the TextView width! I already set the constraints to bounds it on the width of the cell but is not working. there is any function that can help me resize the textView width as the heigh? Thanks.

this is my output now

func adjustUITextViewHeight(arg : UITextView)
    {
        arg.translatesAutoresizingMaskIntoConstraints = true
        arg.sizeToFit()
        arg.isScrollEnabled = false
    }

Solution

  • I solved using this function:

    func adjustUITextViewHeight(arg : UITextView, viewBox : UIView)
    {
        arg.isScrollEnabled = false
        let size = CGSize(width: viewBox.frame.width, height: .infinity)
        let estimatedSize = arg.sizeThatFits(size)
    
        arg.constraints.forEach { (constraint) in
            if constraint.firstAttribute == .height {
                constraint.constant = estimatedSize.height
            }
        }
    
    }
    

    Here is the link to the video-tutorial: https://www.youtube.com/watch?v=0Jb29c22xu8