我有一个 UITextView,当输入超出其框架边界的文本时,它的高度会动态变化。但是,只有在键入完整字符串并按下空格键后,高度才会改变。这会留下一个尴尬的时刻,用户看不到他们正在输入的单词。
如何让我的 textViewDidChange
对输入的每个字符使用react,而不是在输入完整字符串时使用react?
这是初始化变量:
lazy var descriptionTextView: UITextView = {
let tv = UITextView()
tv.backgroundColor = .white
tv.font = UIFont.systemFont(ofSize: 18)
tv.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
tv.translatesAutoresizingMaskIntoConstraints = false
tv.delegate = self
tv.isScrollEnabled = false
return tv
}()
然后我将它添加到 subview 并将其锚定在我的 viewDidLoad
中:
view.addSubview(descriptionTextView)
descriptionTextView.anchor(top: privacyLabel.bottomAnchor, left:
view.leftAnchor, bottom: descriptionTextViewUnderLine.topAnchor, right: view.rightAnchor, paddingTop: 16, paddingLeft: 24, paddingBottom: 0, paddingRight: 24, width: 0, height: 40)
在扩展中,我放了 textViewDidChange
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: view.frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
预先感谢您的帮助!
最佳答案
textViewDidChange(...)
实际上应该对每个输入的字符使用react(通过键盘,而不是以编程方式)。 textView.sizeThatFits(...)
可能没有返回您想要的内容。快速查看文档并没有发现对 UIView 实现的覆盖,它只返回相同大小的 View 。
NSAttributedString 的 boundingRect(with:options:context:)可能值得研究以恢复所需的文本大小(以及 View 的大小)。
另请注意我对您的问题的评论。将 scrollEnabled
设置为 false 应该已经将 textView 的固有大小设置为您需要的大小,您甚至不必设置高度限制。如果您的 textView 在具有相同优先级约束的 View 之间被挤压,您可以沿垂直轴提高 compressionResistancePriority
。
一个快速片段来说明这个例子(不是你问题的答案,但可能是你想做的事情的不同方法):
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController, UITextViewDelegate {
private lazy var textView = UITextView()
override func loadView() {
let view = UIView()
view.backgroundColor = .orange
textView.frame = view.bounds
textView.backgroundColor = .white
textView.isScrollEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textView)
NSLayoutConstraint.activate(
[textView.topAnchor.constraint(equalTo: view.topAnchor),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor)]
)
textView.delegate = self
self.view = view
}
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
关于ios - textViewDidChange 仅在键入完整字符串时发生变化。我想让它检查每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54445756/