带锚点的自动布局边距 [英] Auto-layout margins with anchors

查看:113
本文介绍了带锚点的自动布局边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I thought the following was equivalent?

# 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

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

Though I appear to be wrong. How would I get the 5 margin between the containerView and the parent using margins, constraints and anchors?

推荐答案

我通过阅读以下问题找到了解决方案:自动版式:layoutMarginsGuide .

I found a solution by reading this question: Auto Layout: layoutMarginsGuide.

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

There seems to be an issue when setting layoutMargins from the init.

尽管,我没有在viewDidMoveToSuperView中设置layoutMargins,而是将其放在updateConstraints中,效果也很好.

Though, instead of setting layoutMargins in viewDidMoveToSuperView I put it in updateConstraints instead, which also worked fine.

现在的代码是:

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

与以下内容具有相同的作用:

which then had the same effect as:

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

这篇关于带锚点的自动布局边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆