rightAnchor constraint did not apply when added programmatically - swift

♀尐吖头ヾ 提交于 2019-12-02 14:33:05

问题


When I Added rightAnchor constraint, constant= 20 did not apply. In leftAnchor is ok

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)])
}

Can someone help me?


回答1:


I have a really strong feeling that this is what you wanted to do there for rightAnchor.

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

If you want padding from the right or bottom you should use negative values.


Rule of thumb: Whatever is left or upwards of something is negative.




回答2:


You are adding 20+rightAnchor of your superview. It should be -20

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)])


来源:https://stackoverflow.com/questions/51394989/rightanchor-constraint-did-not-apply-when-added-programmatically-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!