【发布时间】:2020-05-23 08:00:27
【问题描述】:
我在 inputContainerView 中有一个 uitextview subview,因为它可能出现在消息传递应用程序中。
以编程方式,在加载时,uitextview 的高度锚点在 inputContainerView 初始化时设置。当键入更多的文本行时,此约束在增加容器高度方面非常有效。
我的目标是在达到 X 行后限制 uitextview 的高度,此后键入的任何行都可以滚动。同样,当行数低于最大值时,它会返回其原始形式 - 不可滚动并根据内容自动调整高度。
经过多次试验和研究,一旦达到最大行数,我已经设法获得固定的高度,但是一旦行数下降到以下,我似乎无法弄清楚如何将其恢复为原始形式最大。 uitextview 的高度似乎停留在行数已达到最大值的高度。
以下是相关代码:
//Container View Initialization, onLoad Frame Height is set to 60
override init(frame: CGRect) {
super.init(frame: frame)
autoresizingMask = .flexibleHeight
addSubview(chatTextView)
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: frame.height - 20).isActive = true
}
//TextView Delegate
var isTextViewOverMaxHeight = false
var textViewMaxHeight: CGFloat = 0.0
func textViewDidChange(_ textView: UITextView) {
let numberOfLines = textView.contentSize.height/(textView.font?.lineHeight)!
if Int(numberOfLines) > 5 {
if !isTextViewOverMaxHeight {
containerView.textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 40).isActive = false
containerView.textView.heightAnchor.constraint(equalToConstant:
containerView.textView.frame.height).isActive = true
containerView.textView.isScrollEnabled = true
textViewMaxHeight = containerView.textView.frame.height
isTextViewOverMaxHeight = true
}
} else {
if isTextViewOverMaxHeight {
containerView.textView.heightAnchor.constraint(equalToConstant: textViewMaxHeight).isActive = false
containerView.textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 40).isActive = true
containerView.textView.isScrollEnabled = false
isTextViewOverMaxHeight = false
}
}
}
【问题讨论】:
-
解决了你的问题吗?
标签: ios swift uitextview nslayoutconstraint uitextviewdelegate