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

后端 未结 7 1922
离开以前
离开以前 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 05:09

    Create a class that inherits from UITextView and add the following into the class:

    class CustomTextView: UITextView, UITextViewDelegate {
    
        override init(frame: CGRect, textContainer: NSTextContainer?) {
            super.init(frame: frame, textContainer: textContainer)
    
            delegate = self
        }
    
        var maxHeight: CGFloat = 200
    
        override var intrinsicContentSize: CGSize {
            var size = super.intrinsicContentSize
            if size.height > maxHeight {
                size.height = maxHeight
                isScrollEnabled = true
            } else {
                isScrollEnabled = false
            }
            return size
        }
    
        override var text: String! {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
    
        func textViewDidChange(_ textView: UITextView) {
            invalidateIntrinsicContentSize()
        }
    
    }
    

    Note: - You can initialize maxHeight to infinity and set maxHeight after creating the CustomTextView. This class can be reused anywhere it is needed in the app, and the max height can be modified for different scenarios.

提交回复
热议问题