Swift 4-如何在编程使用约束后获得UIView的边界

Swift 4-如何在编程使用约束后获得UIView的边界,swift,autolayout,constraints,bounds,Swift,Autolayout,Constraints,Bounds,在这个问题上我真的需要你的帮助。我正在以编程方式创建UIView对象,而不设置边界。创建后,我向该视图添加约束,以适应屏幕中所需的位置 但问题是,我想在代码的以下部分使用UIView的bounds属性,但不幸的是,我无法获得屏幕上显示的约束集之后的边界 下面是我的示例代码: let previewView = UIView() NSLayoutConstraint(item: previewView, attribute: .top, relatedBy: .equal,

在这个问题上我真的需要你的帮助。我正在以编程方式创建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

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

如何获得屏幕上显示的边界以及相关的Constaint设置

非常感谢各位。

您可以在

 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once { 
        once = false
        // process here
        print(previewView.bounds) 
    } 
 }
但是首先将视图声明为实例变量,在视图中设置
one=false

var previewView:UIView! 
var once= true

看这里

嗨,我的朋友,当我尝试你的建议时,我能得到我所需要的。但这意味着我应该将代码从viewDidLoad移到viewDidLayoutSubviews()。你认为这有意义吗?你是对的。我在我的Mac电脑上也尝试了同样的方法:)但我无法决定将代码移动到viewDidLayoutSubviews是否是一种好方法。您的建议是什么?您可以这样做,但将所有代码包装在Once bool变量中,因为此方法被多次调用哈哈,您的意思是我应该在执行代码之前检查它是否是第一次?只需在调用
preview.superview.layoutIfNeeded()后打印边界即可。