【发布时间】:2017-04-05 07:56:45
【问题描述】:
我需要支持 UITableViewAutomaticDimension(用于动态高度),但约束有所不同:有些需要激活,有些不需要。
我在安装了aConstraint 未 和bConstraint 的情况下设置了情节提要。我在tableView(_:cellForRowAt:) 中根据需要激活/停用它们。
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.estimatedRowHeight = 10
tableView.rowHeight = UITableViewAutomaticDimension
}
}
}
class MyTableViewCell: UITableViewCell {
@IBOutlet var aConstraint: NSLayoutConstraint!
@IBOutlet var bConstraint: NSLayoutConstraint!
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell
cell.contentView.translatesAutoresizingMaskIntoConstraints = false
if indexPath.row % 2 == 0 {
NSLayoutConstraint.deactivate([cell.aConstraint])
NSLayoutConstraint.activate([cell.bConstraint])
} else {
NSLayoutConstraint.deactivate([cell.bConstraint])
NSLayoutConstraint.activate([cell.aConstraint])
}
return cell
}
}
问题
初始可见布局忽略所有这些激活/停用,所有单元格都与原始情节提要状态相同。
您会注意到只有在滚动后才会应用正确的约束。
尝试
我确实尝试了一些cell.setNeedsUpdateConstraints(); cell.updateConstraintsIfNeeded(); cell.layoutIfNeeded(); ...但没有成功
【问题讨论】:
标签: ios swift uitableview uikit nslayoutconstraint