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

后端 未结 7 1979
离开以前
离开以前 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:19

    Maybe the code below is a little better.

    import UIKit
    
    let width = UIScreen.mainScreen().bounds.width
    
    class ViewController: UIViewController, UITextViewDelegate {
    
        var messageTextView: UITextView!
        let messageTextViewMaxHeight: CGFloat = 100
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = UIColor.redColor()
            messageTextView = UITextView(frame: CGRectMake(0, 200 - 33, width, 33))
            messageTextView.backgroundColor = UIColor.whiteColor()
            view.addSubview(messageTextView)
            self.messageTextView.delegate = self
        }
    
        //
        let bottomY: CGFloat = 200
    
        func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
            if text == "\n"{
                let formerRect = textView.frame
                let contentSize = textView.contentSize
                if contentSize.height < formerRect.height{
                    //
                }
                else{
                    if contentSize.height >= messageTextViewMaxHeight{
                        //
                    }
                    else{
                        textView.frame = CGRectMake(formerRect.origin.x, bottomY - contentSize.height, width, contentSize.height)
                    }
                }
            }
            return true
        }
    
    }
    

提交回复
热议问题