【问题标题】:How to remove the top and left margin of a tableView's cell that doesn't expect to preserve the super view's inherited margins?如何删除不希望保留超级视图继承边距的 tableView 单元格的顶部和左侧边距?
【发布时间】:2016-06-21 10:58:00
【问题描述】:

最初,我有一个利用默认 layoutMargin 的单元格

(lldb) po self.contentView.layoutMargins
▿ UIEdgeInsets
  - top : 8.0
  - left : 8.0 { ... }
  - bottom : 8.0 { ... }
  - right : 8.0 { ... }

我希望我的表格视图在利用布局边距的同时自动调整单元格大小,因此,我完成了这个设置一些约束:

NSLayoutConstraint.activateConstraints([
    NSLayoutConstraint(item: self.stackView, attribute: .Top, relatedBy: .Equal, toItem: self.contentView, attribute: .TopMargin, multiplier: 1, constant: 0),
    NSLayoutConstraint(item: self.stackView, attribute: .Bottom, relatedBy: .Equal, toItem: self.contentView, attribute: .BottomMargin, multiplier: 1, constant: 0),
    NSLayoutConstraint(item: self.stackView, attribute: .Leading, relatedBy: .Equal, toItem: self.contentView, attribute: .LeadingMargin, multiplier: 1, constant: 0),
    NSLayoutConstraint(item: self.stackView, attribute: .Trailing, relatedBy: .Equal, toItem: self.contentView, attribute: .TrailingMargin, multiplier: 1, constant: 0)
    ])

目前看起来不错!

我现在想手动更新我的 contentView 的 layoutMargin,所以我这样做了:

self.contentView.preservesSuperviewLayoutMargins = false
self.contentView.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)

我希望将所有现有的插图设置为 0。他们是!说实话:

(lldb) po self.contentView.layoutMargins
▿ UIEdgeInsets
  - top : 0.0
  - left : 0.0 { ... }
  - bottom : 0.0 { ... }
  - right : 0.0 { ... }

但是,我的界面是这样的:

是什么导致我的单元格的顶部和左侧边距具有该边距?

我在这里错过了什么?

谢谢!

【问题讨论】:

  • 我没有直接的答案,但您可能想使用 Xcode 的查看调试功能来捕获屏幕并查看运行时影响间距的因素。
  • 使用 IB 时的好建议。我实际上是添加了 2 个附加约束,其中包含我忘记的前导常量和顶部常量。现在已经修好了。

标签: swift uitableview autolayout nslayoutconstraint


【解决方案1】:

问题中描述的解决方案实际上可以正常工作。但是,我忘记了代码中的一些限制:

NSLayoutConstraint(item: self.stackView, attribute: .Leading, relatedBy: .Equal, toItem: self.contentView, attribute: .Leading, multiplier: 1, constant: 15),
NSLayoutConstraint(item: self.stackView, attribute: .Top, relatedBy: .Equal, toItem: self.contentView, attribute: .Top, multiplier: 1, constant: 15)

这些限制当然是添加了我不希望的顶部和领先边距。

我对任何面临类似问题的人的建议是密切关注在整个代码中添加的所有约束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2012-07-22
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多