编程约束 - 使用布局锚覆盖整个超级视图
Posted
技术标签:
【中文标题】编程约束 - 使用布局锚覆盖整个超级视图【英文标题】:programmatic constraints - cover entire superview using layout anchors 【发布时间】:2016-10-28 08:37:47 【问题描述】:是否可以使用布局锚点覆盖整个超级视图的屏幕?
使用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 个边的填充。
【问题讨论】:
【参考方案1】:您正在限制边距,边距是您看到的空间。改为使用 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
【讨论】:
【参考方案2】:您必须使用属性.leading
、.trailing
、.top
和.bottom
,而不是对应的.xxxMargin
属性。他们将沿着 superviews 边界放置子视图。
【讨论】:
以上是关于编程约束 - 使用布局锚覆盖整个超级视图的主要内容,如果未能解决你的问题,请参考以下文章