How to change the TextView height dynamicly to a threshold and then allow scrolling?

后端 未结 7 1966
离开以前
离开以前 2020-12-16 04:39

I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it

7条回答
  •  旧时难觅i
    2020-12-16 05:21

    This follows a similar approach to the accepted answer but ensures the textView is fully constrained in both height states.

    (There's a bug in the accepted answer - using a height constraint with a <= relation is insufficient to fully constrain the textView when scrolling is enabled, since in this case the view provides no intrinsicContentSize. You can see this in IB (with scrolling disabled), or at runtime via view debugging.)

    This is all that's necessary:

    // In IB, set the relation to `=` and the constant to your desired threshold point
    // Notice this is a strong reference (since the constraint may get deactivated) 
    @IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
    
    func textViewDidChange(textView: UITextView)
    {       
        let isOversize = textView.contentSize.height >= textViewHeightConstraint.constant
        textViewHeightConstraint.isActive = isOversize
        textView.isScrollEnabled = isOversize
    }
    

    There's no need to set frames manually, since in both cases auto-layout has us covered.

提交回复
热议问题