为什么viewDidLayoutSubviews仅在首次运行时被调用两次?

时间:2016-05-14 13:20:48

标签: ios swift2 viewdidlayoutsubviews

这让我很疯狂。只有在第一次运行时才会调用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
    }


}

2 个答案:

答案 0 :(得分:4)

无法保证调用viewDidLayoutSubviews的次数。

您可以在此Stack Overflow帖子中找到一个很好的讨论:
When is layoutSubviews called?

答案 1 :(得分:1)

我发现this article很有用。它的内容摘要如下:

  
      
  • init不会导致layoutSubviews被调用(duh)
  •   
  • addSubview导致在添加的视图,要添加到的视图(目标视图)以及目标视图的所有子视图中调用layoutSubviews
  •   只有当框架的尺寸参数不同时,
  • setFrame智能地调用layoutSubviews视图上的UIScrollView
  •   
  • 滚动layoutSubviews会导致在scrollView上调用layoutSubview,这是超级视图
  •   
  • 旋转设备仅在父视图(响应viewControllers主视图)上调用removeFromSuperview
  •   
  • layoutSubviews - 仅在超级视图中调用{{1}}(未在表格中显示)
  •