我有一个应用程序,其中具有聊天功能,使用UITextview
输入消息。 UITextview
的高度必须是动态的(如果用户输入消息,则根据文本长度更改高度,直到特定高度为止)。
我该如何实现这一点?
我有一个应用程序,其中具有聊天功能,使用UITextview
输入消息。 UITextview
的高度必须是动态的(如果用户输入消息,则根据文本长度更改高度,直到特定高度为止)。
我该如何实现这一点?
增加高度到特定值,然后启用滚动。
提供最大高度约束,然后将此代码添加到您的viewController中。
class YourViewController: UIViewController, UITextViewDelegate
{
@IBOutlet weak var yourTextView: UITextView!
let textViewMaxHeight: CGFloat = 100
override func viewDidLoad()
{
super.viewDidLoad()
yourTextView.delegate = self
}
func textViewDidChange(textView: UITextView)
{
if textView.contentSize.height >= self.textViewMaxHeight
{
textView.scrollEnabled = true
}
else
{
textView.frame.size.height = textView.contentSize.height
textView.scrollEnabled = false
}
}
}
为您的textView添加高度约束,并创建一个outlet以便您可以调整它。然后,您可以使用UITexfield委托方法textViewDidChange(_ textView: UITextView)来调整高度。
func textViewDidChange(_ textView: UITextView) {
// get the current height of your text from the content size
var height = textView.contentSize.height
// clamp your height to desired values
if height > 90 {
height = 90
} else if height < 50 {
height = 50
}
// update the constraint
textViewHeightConstraint.constant = height
self.view.layoutIfNeeded()
}
func textViewDidChange(_ textView: UITextView) {
let maxHeight: CGFloat = 90.0
let minHeight: CGFloat = 50.0
textViewHeightConstraint.constant = min(maxHeight, max(minHeight, textView.contentSize.height))
self.view.layoutIfNeeded()
}
class Message: UITextView {
var maximalSizeNotScrollable: CGFloat = 200
var minimumHeightTextView: CGFloat = 35
var textViewHeightAnchor: NSLayoutConstraint!
override var contentSize: CGSize {
didSet {
if textViewHeightAnchor != nil {
textViewHeightAnchor.isActive = false
}
textViewHeightAnchor = heightAnchor.constraint(equalToConstant: min(maximalSizeNotScrollable, max(minimumHeightTextView, contentSize.height)))
textViewHeightAnchor.priority = UILayoutPriority(rawValue: 999)
textViewHeightAnchor.isActive = true
self.layoutIfNeeded()
}
}
}
优先级必须小于1000,否则您将遇到_UITemporaryLayoutHeight的问题。
我曾经也遇到过同样的问题。在阅读了@Anuraj的回答后,我将UITextView的高度约束拖放到了视图控制器中,因为当textview达到最大高度并启用滚动时,textview会变小以显示一行,所以我通过给textview的高度约束设置最大高度来解决了这个问题。Textview会扩展直到达到最大高度,之后它将可以滚动。当你删除文本时,textview的高度会自动变小。
@IBOutlet weak var txMessageHeight: NSLayoutConstraint!
let textViewMaxHeight: CGFloat = 120
func textViewDidChange(_ textView: UITextView) {
if textView.contentSize.height >= self.textViewMaxHeight{
txMessageHeight.constant = self.textViewMaxHeight
textView.isScrollEnabled = true
}else{
textView.frame.size.height = textView.contentSize.height
textView.isScrollEnabled = false
}
}
func textViewDidChange(_ textView: UITextView) {
if textView.contentSize.height >= maxHeight {
textView.isScrollEnabled = true
} else {
textView.isScrollEnabled = false
}
}
如果你想在 TextView 内容为空时重置其高度,只需要编写以下代码:
UIView.animate(withDuration: 0.15) {
self.view.layoutIfNeeded()
}