Swift 4 - 如何在以编程方式使用约束后获取 UIView 的边界

Yag*_*zen 4 constraints bounds autolayout swift

我真的需要你在这个问题上的帮助。我正在以编程方式创建一个 UIView 对象,而没有在开始时设置边界。创建后,我向该视图添加约束以适合屏幕中所需的位置。

但问题是,我想在代码的以下部分使用 UIView 的 bounds 属性,但不幸的是,我无法在屏幕上显示的约束设置后获得边界。

下面我有示例代码:

     let previewView = UIView()

     NSLayoutConstraint(item: previewView, attribute: .top, relatedBy: .equal, toItem: upperView, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true

     NSLayoutConstraint(item: previewView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true


    previewView.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true

    previewView.translatesAutoresizingMaskIntoConstraints = false


    print(previewView.bounds)
   // (0.0, 0.0, 0.0, 0.0) ->>>> How can I get the bounds as it shows on the screen instead of 0,0,0,0
Run Code Online (Sandbox Code Playgroud)

在此之后,当我尝试使用 previewView.bounds 属性时,它会将其原始大小返回为 0。

我怎样才能获得屏幕上显示的具有相关约束设置的边界?

非常感谢你们。

Sh_*_*han 5

您可以在

 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once { 
        once = false
        // process here
        print(previewView.bounds) 
    } 
 }
Run Code Online (Sandbox Code Playgroud)

但首先将视图声明为实例变量,once = false在视图中创建

var previewView:UIView! 
var once= true
Run Code Online (Sandbox Code Playgroud)

看这里在此处输入图片说明