带锚点的自动布局边距

net*_*ger 3 cocoa-touch ios autolayout nslayoutconstraint

因此,我认为以下内容是等效的?

# This is how I usually do
contentView.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
contentView.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -5).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true

# This is what I tried. I expected the same result..
layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
contentView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true
Run Code Online (Sandbox Code Playgroud)

虽然我似乎是错的。我如何使用边距,约束和锚点在containerView和父级之间获得5个边距?

net*_*ger 5

通过阅读以下问题,我找到了一个解决方案:自动布局:layoutMarginsGuide

layoutMargins从设置时似乎存在问题init

虽然,而不是设置layoutMarginsviewDidMoveToSuperView我把它放在updateConstraints代替,这也工作得很好。

现在的代码是:

override init(frame: CGRect) {
    super.init(frame: frame)
    contentView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor).isActive = true
    contentView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true
    contentView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
    contentView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true
}

override func updateConstraints() {
    super.updateConstraints()
    layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
Run Code Online (Sandbox Code Playgroud)

然后具有与以下相同的效果:

contentView.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
contentView.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -5).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true
Run Code Online (Sandbox Code Playgroud)