以编程方式添加时,rightAnchor 约束不适用 - swift

Yur*_*ick 1 constraints ios swift ios-autolayout

当我添加 rightAnchor 约束时,constant= 20 不适用。在leftAnchor就可以了

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(collectionView)
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([collectionView.leftAnchor.constraint(equalTo: leftAnchor, constant: 20),
                                 collectionView.topAnchor.constraint(equalTo: self.topAnchor),
                                 collectionView.rightAnchor.constraint(equalTo: rightAnchor, constant: 20),
                                 collectionView.heightAnchor.constraint(equalTo: self.heightAnchor)])
}
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

Rak*_*tri 7

我有一种强烈的感觉,这就是你想要在那里做的事情rightAnchor

collectionView.rightAnchor.constraint(equalTo: rightAnchor, constant: -20)

如果您想从右侧或底部填充,则应使用负值。


经验法则:任何东西剩下的或上面的都是负面的。