Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

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

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 reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var messageTextView: UITextView!
let messageTextViewMaxHeight: CGFloat = 100

override func viewDidLoad() {
    super.viewDidLoad()
    self.messageTextView.delegate = self
}

func textViewDidChange(textView: UITextView) {

    if textView.frame.size.height >= self.messageTextViewMaxHeight {
        textView.scrollEnabled = true
        textView.frame.size.height = self.messageTextViewMaxHeight
    } else {
        textView.scrollEnabled = false
    }
}
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems your code requires two changes, and it will work fine.

  1. Instead of min height of constraint provide max height of 100:

Height Constraint for TextView

  1. Change code as below:

     import UIKit
    
    class ViewController: UIViewController, UITextViewDelegate
    {
        @IBOutlet weak var messageTextView: UITextView!
    
        let messageTextViewMaxHeight: CGFloat = 100
        override func viewDidLoad()
        {
            super.viewDidLoad()
            messageTextView.delegate = self
        }
    
        func textViewDidChange(textView: UITextView)
        {
            if textView.contentSize.height >= self.messageTextViewMaxHeight
            {
                textView.scrollEnabled = true
            }
            else
                {
                textView.frame.size.height = textView.contentSize.height
                textView.scrollEnabled = false // textView.isScrollEnabled = false for swift 4.0
            }
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...