gpt4 book ai didi

ios - 编程约束 - 使用布局 anchor 覆盖整个父 View

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:52 25 4
gpt4 key购买 nike

是否可以使用布局 anchor 来覆盖整个父 View 的屏幕?

使用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

我想改为切换到布局 anchor ,遵循 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

但两者均无效。我最终得到的不是完全覆盖 containerview,而是在所有 4 个边上填充。

enter image description here

最佳答案

您受限于页边距,页边距就是您看到的空间。改为约束到 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

关于ios - 编程约束 - 使用布局 anchor 覆盖整个父 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com