swift2 为什么viewDidLayoutSubviews只在第一次运行时调用两次?

e7arh2l6  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(169)

这让我抓狂。只有在第一次运行时,viewDidLayoutSubviews才被调用两次。
下面是我使用的代码:

class CICViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func addQLabel(qLabel: UILabel, questionString: String, bgrLabel: UILabel) {// some code goes here
    }

    func makeRoundQButtons(qButtons:[UIButton]) {
      // some code goes here

    }

    func addArrows(numberOfArrows:Int, buttonCurAngle:Double) {//some code goes here
    }

    func animateButtons(qButtons:[UIButton], buttonCurAngle:Double) {

     // some code goes here

    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

    }

    func backTapped(sender: UIBarButtonItem) {
        navigationController?.popViewControllerAnimated(false)
       //some code goes here

    }

    func restartTapped(sender: UIBarButtonItem) {
        navigationController?.popToRootViewControllerAnimated(false)
        //some code goes here
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

在我的ViewController中,我称之为:

class OneViewController: CICViewController {

  override func viewDidLoad() {
        super.viewDidLoad()

 //some code goes here
}

    override func viewDidLayoutSubviews() {

        super.viewDidLayoutSubviews()
        print("viewDidLayoutSubviews")
        self.makeRoundQButtons(qButtons)
        self.animateButtons(qButtons, buttonCurAngle: 2.0)

    }

    override func viewDidAppear(animated: Bool) {
     //nothing goes here
    }

}
cbeh67ev

cbeh67ev1#

不保证viewDidLayoutSubviews将被调用多少次。
您可以在这篇Stack Overflow文章中找到一个很棒的讨论:
When is layoutSubviews called?

vnzz0bqm

vnzz0bqm2#

我发现this article很有用。总结一下它的内容:

  • init不会导致呼叫layoutSubviews(duh)
  • addSubview会导致在要添加的视图、要添加到的视图(目标视图)以及目标视图的所有子视图上调用layoutSubviews
  • setFrame仅在帧的大小参数不同时,才对设置了帧的视图智能地调用layoutSubviews
  • 滚动UIScrollView会导致在scrollView上调用layoutSubviews,并且它是superview
  • 旋转设备仅调用父视图上的layoutSubview(响应的viewControllers主视图)
  • removeFromSuperview-layoutSubviews仅在超级视图上调用(未在表中显示)

相关问题