问题
I need to have a nested UITableView in a tableView cell (actually, two tables in one cell) to show different lists with dynamic content (so, I need dynamic heights). My nested tables will not have scrolling—I need them just to order elements of different kinds, like texts, pictures, fields etc. To be more clear—the first level is the level of operations and every operation can have a variable amount of instructions and actions. Instructions and actions should be placed side by side and the operation cell should have the size of the tallest table.
There are no problems in nesting tables, but I faced a problem with the auto layout. I’ve tried everything that I could find, but with no success.
I tried height constraints for nested table views, which I update on the operation cell creation from tableview.contentsize.hight, but it seems that contentsize returns height based on the estimated size of every row, but not the actual size.
I tried to rewrite intrinsic content size of nested tables:
UITableView {
override var contentSize:CGSize {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height)
}
}
Nothing works properly. Any ideas how it could be solved?
Thank you in advance.
回答1:
Set Inner tableview my custom class AGTableView
and height Constraint both are required,
this class set contantSize
same table view height Constraint.
Check out Github AutoHeightIncrementTableViewDemo
class AGTableView: UITableView {
fileprivate var heightConstraint: NSLayoutConstraint!
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.associateConstraints()
defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.associateConstraints()
defaultInit()
}
func defaultInit(){
self.keyboardDismissMode = .onDrag
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.tableFooterView = UIView(frame: .zero)
self.tableHeaderView = UIView(frame: .zero)
self.sectionFooterHeight = 0
self.sectionHeaderHeight = 0
}
override open func layoutSubviews() {
super.layoutSubviews()
if self.heightConstraint != nil {
self.heightConstraint.constant = self.contentSize.height
}
else{
print("Set a heightConstraint to set cocontentSize with same")
}
}
func associateConstraints() {
// iterate through all text view's constraints and identify
// height
for constraint: NSLayoutConstraint in constraints {
if constraint.firstAttribute == .height {
if constraint.relation == .equal {
heightConstraint = constraint
}
}
}
}
}
NOTE: Also set a estimatedRowHeight
self.rowHeight = UITableViewAutomaticDimension
self.estimatedRowHeight = height
来源:https://stackoverflow.com/questions/48941167/nested-uitableview-dynamic-height