Mid*_*yan 4 uitextview ios swift
我有一个具有聊天功能的应用程序,UITextview用于输入消息.UITextview高度必须是动态的(如果用户输入消息,则必须根据文本长度更改高度,直到特定高度).
我怎样才能做到这一点?
禁用滚动textView.
要将高度增加到特定值,然后启用滚动.
提供最大高度约束,然后将此代码添加到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
}
}
}
Run Code Online (Sandbox Code Playgroud)
向 textView 添加高度约束并创建一个出口,以便您可以对其进行调整。然后就可以使用 UIExfield 委托方法 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()
}
Run Code Online (Sandbox Code Playgroud)
较短的版本...
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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3693 次 |
| 最近记录: |