【发布时间】:2017-04-16 17:51:00
【问题描述】:
我一直在尝试遵循this github 教程,但是它们不是静态单元格,而是动态的,因为我不知道编译时的高度。
在 tableViewController 中,我将heightForRowAt 设置为0 或UITableViewAutomaticDimension,具体取决于该部分是否折叠。与estimatedHeightForRowAt类似,该值是0,如果展开,则为更高的值。
现在解决问题,我已将UITableViewCell 子类化,当调用 cellForRowAt 时,它将添加一个如下所示的子视图:
override func addSubview(_ view: UIView) {
guard view != nil else {return}
for view in self.subviews {
view.removeFromSuperview()
}
super.addSubview(view)
//view.applyLeadingAndTrailingPinConstraint(toSuperview: 0)
//view.applyTopAndBottomPinConstraint(toSuperview: 0)
let addedView = self.subviews[0]
let bottom = NSLayoutConstraint(item: addedView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
bottom.priority = 750
bottom.isActive = true
NSLayoutConstraint(item: addedView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: addedView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: addedView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: addedView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: addedView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
//NSLayoutConstraint.reportAmbiguity(v: self)
if addedView.hasAmbiguousLayout {
print("Horizontal: \(addedView.constraintsAffectingLayout(for: .horizontal))")
print("Vertical: \(addedView.constraintsAffectingLayout(for: .vertical))")
print("Trace: \(addedView.value(forKey: "_autolayoutTrace"))")
}
//addedView.exerciseAmbiguityInLayout()
//print("self: \(self.frame), subview: \(self.subviews[0].frame)")
}
如您所见,问题在于约束有歧义,因此使用了hasAmbigousLayout。当视图折叠时没有错误。然而,当我展开视图时,也有高度限制,就会出现歧义。以下是hasAmbigousLayout内的3条打印语句的输出:
Horizontal: []
Vertical: [<NSLayoutConstraint:0x60800028ea10 UIView:0x7fcfe856a790.height == 100 (active)>]
Trace: Optional(
•ViraVira_Info.WellnessCell:0x7fcfe8859a00'cell', MISSING HOST CONSTRAINTS
| *UIView:0x7fcfe856a790- AMBIGUOUS LAYOUT for UIView:0x7fcfe856a790.minX{id: 776}, UIView:0x7fcfe856a790.minY{id: 771}, UIView:0x7fcfe856a790.Width{id: 778}
Legend:
* - is laid out with auto layout
+ - is laid out manually, but is represented in the layout engine because translatesAutoresizingMaskIntoConstraints = YES
• - layout engine host)
我已尝试按照this 问题中的建议降低底部约束优先级。我还尝试了许多其他网站,但遗憾的是我忘记了这些网站。 应用程序中的结果是视图甚至没有显示,因为它应该有一个红色背景,当我尝试打印子视图的框架时,宽度为 0,这看起来很奇怪。
我可能在约束方面犯了一个愚蠢的错误,但经过 2 天的尝试,我仍然无法弄清楚。
感谢您的宝贵时间 -豪尔赫
【问题讨论】:
标签: ios swift uitableview dynamic nslayoutconstraint