Ios NSLayoutConstraint边距为零而不是十六
我正在通过代码构建UICollectionViewCell接口。除了正确的约束外,一切正常。当我运行应用程序时,标题标签的右边距为零。这是我的密码Ios NSLayoutConstraint边距为零而不是十六,ios,swift3,nslayoutconstraint,Ios,Swift3,Nslayoutconstraint,我正在通过代码构建UICollectionViewCell接口。除了正确的约束外,一切正常。当我运行应用程序时,标题标签的右边距为零。这是我的密码 let titleLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.purple label.translatesAutoresizingMaskIntoConstraints = false return label }(
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
联系起来。问题是您的约束中项目的顺序。您当前的意思是标签超出其superview的右边缘16。您可以切换右侧约束中的项
和项
,或者使用-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))
将起作用。在添加子视图之前是否加载了单元格大小?如果否,请加载单元格,然后运行setupview,然后运行self.setNeedsDisplay()、self.layoutifneed()。如果是,您也可以尝试运行上述函数。如果您对正确的约束常量使用
-16
,会发生什么情况?@vacawama它可以工作!怎么了?工作得很有魅力!