UITextView
上设置isScrollEnabled
为false
,它就可以在堆栈视图内自行调整大小。问题在于您通过给top
和bottom
约束来固定UIStackView的高度。
禁用TextView滚动。
将您的TextView委托给自己并实现textViewDidChange方法。
Swift
func textViewDidChange(_ textView: UITextView) {
view.layoutIfNeeded()
}
Objective C:
-(void)textViewDidChange:(UITextView *)textView {
[self.view layoutIfNeeded];
}
确保调用此方法。
现在,您的 stackview 应该随着文本视图而多行增长。
您的文本视图不是多行的原因是因为您已经固定了高度。因此,它永远不会成为多行文本。
请参阅 GIF:
let textView = UITextView()
let containerView = UIView()
textView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(textView)
textView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
textView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
textView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
textView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
textView.heightAnchor.constraint(equalToConstant: 100).isActive = true
let stackView = UIStackView(arrangedSubviews: [containerView])