how to make UITextView height dynamic according to text length?

前端 未结 21 2319
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 05:44

As you can see in this image

the UITextView changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te

21条回答
  •  眼角桃花
    2020-11-28 05:49

    SWIFT 4

    Change the size when typing

    UITextViewDelegate

    func textViewDidChange(_ textView: UITextView) {
            yourTextView.translatesAutoresizingMaskIntoConstraints = true
            yourTextView.sizeToFit()
            yourTextView.isScrollEnabled = false
    
            let calHeight = yourTextView.frame.size.height
            yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
        }
    

    Change the size when load

    func textViewNotasChange(arg : UITextView) {
            arg.translatesAutoresizingMaskIntoConstraints = true
            arg.sizeToFit()
            arg.isScrollEnabled = false
    
            let calHeight = arg.frame.size.height
            arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
        }
    

    Call the function of the second option like this:

    textViewNotasChange(arg: yourTextView)
    

提交回复
热议问题