how to make UITextView height dynamic according to text length?

前端 未结 21 2312
隐瞒了意图╮
隐瞒了意图╮ 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 06:09

    If your textView is allowed to grow as tall as the content, then

    textView.isScrollEnabled = false
    

    should just work with autolayout.

    If you want to remain the textView to be scrollable, you need to add an optional height constraint,

    internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
      let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
      constraint.priority = .defaultHigh
      return constraint
    }()
    
    public override func layoutSubviews() {
      super.layoutSubviews()
    
      // Assuming there is width constraint setup on the textView.
      let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
      textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
    }
    

    The reason to override layoutSubviews() is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.

    Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textView will be less than the contentSize. And the textView will be scrollable.

提交回复
热议问题