iOS使用SnapKit设置自动布局后,获取的框架出现错误

4

我在UIStoryboard中添加了一个UIView,并将其绑定到名为testView的自定义UIView类。接下来,在require init函数中创建了一个名为subView的UIView

以下是我的步骤:

1. 初始化subView

2. 将新的subView添加到textView中

3. 设置自动布局

4. 设置cornerRadius (view.frame.height / 2)

运行应用程序后,cornerRadius没有改变。

然后我尝试打印subView的frame,结果为(0,0,0,0)。

以下是我的代码:

required init?(coder aDecoder: NSCoder) {
   super.init(coder: aDecoder)

   circelView = UIView()
   self.addSubview(circelView)
   circelView.snp_makeConstraints(closure: { (make) -> Void in
       make.size.equalTo(80)
       make.top.equalTo(self.snp_top)
       make.right.equalTo(self.snp_right)
   })
   print(circelView.frame) //get wrong frame
   circelView.layer.cornerRadius = circelView.frame.size.height / 2
   circelView.layer.masksToBounds = true
}

你应该能够强制调用 self.layoutSubviews(),然后你就会得到所需的框架。 - Akshit Zaveri
1个回答

4

当你打印框架并设置角半径时,你的视图还没有被布局。添加AutoLayout约束并不会自动布局视图。

为了得到正确的结果,你需要在视图被布局后设置角半径。这将保证你有一个受你的AutoLayout约束限制的框架。

为此,请将任何需要正确框架的代码放置在 'viewDidLayoutSubviews' 中:

override func viewDidLayoutSubviews() {
    print(circelView.frame) // The frame will have been set
    circelView.layer.cornerRadius = circelView.frame.size.height / 2
}

viewDidLayoutSubviews()UIViewController上可以重写的一个方法,您可以在此处查看文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接