Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 为什么在设置约束后我的子视图边界(0,0,0,0)会变大?_Swift - Fatal编程技术网

Swift 为什么在设置约束后我的子视图边界(0,0,0,0)会变大?

Swift 为什么在设置约束后我的子视图边界(0,0,0,0)会变大?,swift,Swift,我正在使用最新版本的swift,并以编程方式编写所有内容。我正在尝试创建一个UIView holderView,它位于顶层视图的安全区域的边界内。此代码返回 (0.0, 0.0, 414.0, 896.0) (0.0, 0.0, 0.0, 0.0) 这表明holderView不受顶层视图的约束。有人能就如何进行提出建议吗?代码如下 class WelcomeViewCon: UIViewController { var holderView = UIView()

我正在使用最新版本的swift,并以编程方式编写所有内容。我正在尝试创建一个UIView holderView,它位于顶层视图的安全区域的边界内。此代码返回

(0.0, 0.0, 414.0, 896.0)
(0.0, 0.0, 0.0, 0.0)
这表明holderView不受顶层视图的约束。有人能就如何进行提出建议吗?代码如下

class WelcomeViewCon: UIViewController {
    
    var holderView = UIView()
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        configure()
    }
    
    private func configure() {
        view.backgroundColor = .systemRed
        
        view.addSubview(holderView)
        holderView.backgroundColor = .systemGray
        let constraints = holderView.constraintsForAnchoringTo(boundsOf: view)
        NSLayoutConstraint.activate(constraints)
        print(view.bounds)
        print(holderView.bounds)
    }
}

extension UIView {

    /// Returns a collection of constraints to anchor the bounds of the current view to the given view.
    ///
    /// - Parameter view: The view to anchor to.
    /// - Returns: The layout constraints needed for this constraint.
    func constraintsForAnchoringTo(boundsOf view: UIView) -> [NSLayoutConstraint] {
        return [
            topAnchor.constraint(equalTo: view.topAnchor),
            leadingAnchor.constraint(equalTo: view.leadingAnchor),
            view.bottomAnchor.constraint(equalTo: bottomAnchor),
            view.trailingAnchor.constraint(equalTo: trailingAnchor)
        ]
    }
}

这只是时间问题。约束在布局完成后才生效。但是您在布局过程中应用了约束(这是完全错误的;这是
updateConstraints
的目的,或者只需在
viewDidLoad
中执行一次),因此在下一个布局之后才能测量结果


此外,布局会发生很多次,因此您的代码会一次又一次地添加子视图和约束。危险的东西。

@Tyler成功了,但是你能解释一下为什么holderView的边界仍然是(0,0,0,0)吗?明白了——会将所有内容切换到viewDidLoad。没错,但即使这样,你也不能在应用约束的同一位置进行测量。它们还没有生效!