ios - 如何将 TextView 高度动态更改为阈值然后允许滚动?

标签 ios swift scroll uitextview

我有一个 TextView,它的最小高度限制为 33。 Storyboard 中禁用了滚动。 TextView 应根据内容增加高度,直到达到最大高度 100。然后我将 scrollEnabled 更改为 true 并将 TextView 的高度更改为最大高度100,但高度变为 33。如何解决此问题?

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

最佳答案

看来您的代码需要进行两处更改,并且可以正常工作。

  1. 而不是约束的最小高度提供最大高度 100:

Height Constraint for TextView

  1. 修改代码如下:

     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
            }
        }
    }
    

关于ios - 如何将 TextView 高度动态更改为阈值然后允许滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415847/

相关文章:

ios - 为适用于不同对象的属性定义宏?

javascript - 如何在 jQuery 中从一个航点滚动到另一个航点?

javascript - 禁用鼠标滚动

iphone - 在 firstResponder 上显示 UITextField 键盘,即使 userInteractionEnabled = NO

ios - addSublayer 不在 View 上添加任何子层

ios - Swift - 向 UIContainerView 添加约束使容器消失

iOS/Swift/Spritekit 在我在该 View Controller 中呈现新场景后,场景是否会删除数据?

objective-c - 如何在 swift 文件中使用 HOST_VM_INFO_COUNT

javascript - WordPress 窗口滚动功能不起作用

ios - 为 iphoneos 构建 live555 库