我想创建可以同时调整大小和滚动的UITextView,就像Telegram,Instagram或Whats App上的一样,允许UITextView最多扩展到8行,如果您向其中添加更多文本,则可以滚动能够使UITextView增长到5行,但是如果它们是更多文本,因为isScroll属性被禁用,我看不到
我的UITextView在UIView的内部,左右两个按钮,如果可能的话,我也希望通过限制来做到这一点,如果不能通过代码也可以的话
答案 0 :(得分:2)
您可以通过以下步骤实现预期的结果:
以下是我要附加的代码段,可能会对您有所帮助:
let commentViewMinHeight: CGFloat = 45.0
let commentViewMaxHeight: CGFloat = 120.0 //In your case it should be 8 lines
func textViewDidChange(_ textView: UITextView) {
//Calculate text height
let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
textViewHeightConstraint.constant = size.height.clamped(to: commentViewMinHeight...commentViewMaxHeight)
if textView.contentSize.height < commentViewMaxHeight {
textView.setContentOffset(CGPoint.zero, animated: false)
if textView.isScrollEnabled {
textView.isScrollEnabled = false
}
} else {
if !textView.isScrollEnabled {
textView.isScrollEnabled = true
}
}
}
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
答案 1 :(得分:1)
Sagar的答案很好,但我想对其进行一些增强并为其添加一些动画:
textViewDidChange
委托方法textViewDidChange
中
textView.sizeThatFits(size)
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!
let maxTextHeight:CGFloat = 200
let minTextHeight:CGFloat = 50
let animationDuration:Double = 0.3
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
resizeTextViewToFitText()
}
func resizeTextViewToFitText() {
let size = CGSize(width: textView.frame.width, height: .infinity)
let expectedSize = textView.sizeThatFits(size)
self.textViewHeightConstraint.constant = max(min(expectedSize.height, self.maxTextHeight), self.minTextHeight)
self.textView.isScrollEnabled = expectedSize.height > self.maxTextHeight
UIView.animate(withDuration: animationDuration) {
self.view.layoutIfNeeded()
}
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
resizeTextViewToFitText()
}
}