我按代码构建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
答案 0 :(得分:2)
问题在于约束中项目的顺序。您目前正在说标签超过其超级视图的右边缘16。您可以在右侧约束中切换item
和toItem
,也可以使用-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))
会奏效。