【发布时间】: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 有关,因为self 是uilabel,我想将它与UICollectionViewCell 关联起来
【问题讨论】:
-
添加子视图之前是否加载单元格大小?如果否,则加载单元格,然后运行 setupViews,然后运行 self.setNeedsDisplay()、self.layoutIfNeeded()。如果是,您也可以尝试运行上述功能。
-
如果你使用
-16作为正确的约束常数会发生什么? -
@vacawama 它有效!怎么样?
标签: ios swift3 nslayoutconstraint