gpt4 book ai didi

swift - 添加 NSLayoutConstraint 后, View 消失

转载 作者:行者123 更新时间:2023-11-30 10:04:14 26 4
gpt4 key购买 nike

当我向 View 添加 NSLayoutConstraint 时,会导致 View 消失。

我正在使用以下代码:

let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100))
test.backgroundColor = UIColor.blackColor()
self.view.addSubview(test)
test.translatesAutoresizingMaskIntoConstraints = false
let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: test.superview, attribute: .CenterX, multiplier: 0.5, constant: 0)
topCKCtr.active = true

let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: test.superview, attribute: .CenterY, multiplier: 0.5, constant: 0)
topCKCtr1.active = true


self.view.layoutIfNeeded()
self.view.setNeedsDisplay()

当我调试 View 层次结构时,我看到 View 存在,即使它不可见。有关详细信息,请参阅下面的屏幕截图 - 只有约束可见,而不是 View : enter image description here

最佳答案

这里需要讨论的事情太多了。

  1. 当您使用以下内容时

    test.translatesAutoresizingMaskIntoConstraints = false

    那么它将完全依赖于约束来定位和调整 View 的大小。因此您需要设置 View 的高度和宽度约束。

    let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)

    let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)

最后这将是您正在寻找的代码

            let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100))
test.backgroundColor = UIColor.blackColor()
self.view.addSubview(test)
test.translatesAutoresizingMaskIntoConstraints = false
let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 0.5, constant: 0)
topCKCtr.active = true
let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 0.5, constant: 0)
topCKCtr1.active = true

let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)
topCKCtr2.active = true

let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)
topCKCtr3.active = true

关于swift - 添加 NSLayoutConstraint 后, View 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928223/

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