[英]How to dynamically resize xib according to UITextView
I am using auto layout. 我正在使用自动布局。
UIView
from xib. UIView
。 UITextView
. UITextView
之外,所有元素都具有静态大小。 ViewDidLoad()
. ViewDidLoad()
上填充了不同大小的文本。 So it can be 1 line or 7 lines there for example. I am loading this UIView with the following method: 我正在使用以下方法加载此UIView:
fileprivate func setTableHeaderView() {
guard let _headerView = UINib(nibName: "TableHeaderView",
bundle: nil).instantiate(withOwner: self, options: nil)[0] as? UIView else { return }
tableView.tableHeaderView = UIView(frame:
CGRect(x: 0, y: 0, width: tableView.frame.width, height: _headerView.frame.size.height))
configureViewController() // here I set the text for UITextView
tableView.tableHeaderView?.addSubview(_headerView)
}
When I load this UIView
the height is always the same both before and after layoutSubviews
. 当我加载此
UIView
, layoutSubviews
之前和之后的高度始终相同。 Actually the size always is equal to the initial size of the xib that is set in the Size Inspector of XCode. 实际上,大小始终等于XCode 大小检查器中设置的xib的初始大小。
I want to UITextView
to fit the text size and to have different xib UIView size that will depend on the size of UITextView
+ all other elements + constraints. 我想让
UITextView
适应文本大小并具有不同的xib UIView大小,这取决于UITextView
+所有其他元素+约束的大小。
I've tried different ways to implement this but but none did not help. 我尝试了不同的方法来实现这一点,但没有一个方法没有帮助。 What I've tried:
我尝试过的
translatesAutoresizingMaskIntoConstraints = true
with autoresizingMask = .flexibleHeight
autoresizingMask = .flexibleHeight
translatesAutoresizingMaskIntoConstraints = true
autoresizingMask = .flexibleHeight
Is it possible to implement this idea in such way? 有可能以这种方式实现这一想法吗?
Try to override viewDidLayoutSubviewsMethod 尝试覆盖viewDidLayoutSubviewsMethod
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Dynamic sizing for the header view
if let headerView = tableView.tableHeaderView {
let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var headerFrame = headerView.frame
// If we don't have this check, viewDidLayoutSubviews() will get
// repeatedly, causing the app to hang.
if height != headerFrame.size.height {
headerFrame.size.height = height
headerView.frame = headerFrame
tableView.tableHeaderView = headerView
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.