【问题标题】:NSLayoutConstraint margin zero instead of sixteenNSLayoutConstraint 边距为零而不是十六
【发布时间】:2017-01-11 15:46:16
【问题描述】:

我正在通过代码构建 UICollectionViewCell 界面。一切正常,除了正确的约束。当我运行应用程序时,标题标签的右边距为零。这是我的代码

let titleLabel: UILabel = {
    let label = UILabel()
    label.backgroundColor = UIColor.purple
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

func setupViews() {
    addSubview(titleLabel)

    // titleLabel
    // top constraint
    addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 16))
    // left constraint
    addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 8))
    // right constraint
    addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 16))
    // height constraint
    addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))
}

我认为它与toItem: self 有关,因为selfuilabel,我想将它与UICollectionViewCell 关联起来

【问题讨论】:

  • 添加子视图之前是否加载单元格大小?如果否,则加载单元格,然后运行 ​​setupViews,然后运行 ​​self.setNeedsDisplay()、self.layoutIfNeeded()。如果是,您也可以尝试运行上述功能。
  • 如果你使用-16作为正确的约束常数会发生什么?
  • @vacawama 它有效!怎么样?

标签: ios swift3 nslayoutconstraint


【解决方案1】:

问题是约束中项目的顺序。您当前说的是标签在其超级视图的右边缘 16 处。您可以在右约束中切换itemtoItem,或使用-16 作为常量。

所以要么这样:

addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: 16))

或者这个:

addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -16))

会起作用的。

【讨论】:

  • 工作就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多