程序化约束 - 使用布局锚

时间:2016-10-28 08:37:47

标签: ios swift nslayoutconstraint nslayoutanchor

是否可以使用布局锚来覆盖整个superview的屏幕?

使用NSLayoutConstraints,我可以使用下面的代码实现这个效果

dimmingView = UIView()
dimmingView.translatesAutoresizingMaskIntoConstraints = false
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)

containerView?.addSubview(dimmingView)

NSLayoutConstraint(item: containerView!, attribute: .leadingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .leadingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .trailingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .trailingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .topMargin, relatedBy: .equal, toItem: dimmingView, attribute: .topMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .bottomMargin, relatedBy: .equal, toItem: dimmingView, attribute: .bottomMargin, multiplier: 1, constant: 0).isActive = true

我希望切换到布局锚点,遵循docs中建议的内容。我试过这样做:

let margins = containerView?.layoutMarginsGuide

dimmingView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
dimmingView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
dimmingView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
dimmingView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true

或者

let margins = containerView?.layoutMarginsGuide

dimmingView.heightAnchor.constraint(equalTo: margins.heightAnchor).isActive = true
dimmingView.widthAnchor.constraint(equalTo: margins.widthAnchor).isActive = true
dimmingView.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
dimmingView.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true

但两者都不起作用。而不是完全覆盖容器视图,我最终得到的是所有4个边的填充。

enter image description here

2 个答案:

答案 0 :(得分:4)

您正在限制边距,边距是您看到的空间。限制为superview:。

    dimmingView.heightAnchor.constraint(equalTo: dimmingView.superview!.heightAnchor).isActive = true
    dimmingView.widthAnchor.constraint(equalTo: dimmingView.superview!.widthAnchor).isActive = true
    dimmingView.centerXAnchor.constraint(equalTo: dimmingView.superview!.centerXAnchor).isActive = true
    dimmingView.centerYAnchor.constraint(equalTo: dimmingView.superview!.centerYAnchor).isActive = true

答案 1 :(得分:0)

您必须使用.leading.trailing.top.bottom这些属性,而不是相应的.xxxMargin属性。他们会将子视图放在超视图范围内。