cannot update view.layer.frame in viewDidLoad?

前端 未结 5 1884
予麋鹿
予麋鹿 2021-02-19 18:59

I am trying to execute following code in viewDidLoad method of my single view controller project:

self.view.layer.frame = CGRectInset(self.view.layer.frame, 20,          


        
5条回答
  •  感动是毒
    2021-02-19 20:00

    I think the issue you are running into with this line:

    self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);
    

    can be explained like so :

    • in viewDidLoad, the properties are set, but the frame of the views are not yet defined.
    • by the time viewWillAppear is triggered, they will be set. That explains why that line of code works there.
    • But since iOS 5, there is another method called after viewDidLoad and before viewWillAppear in which the view frames are set : viewDidLayoutSubviews.

    You can find the complete explanation of this in this season's Stanford CS193P course about iOS programming (very cool by the way).

    So if you want it to work just once, use :

    - (void)viewDidLayoutSubviews
    {
        self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);
    }
    

    PS : I posted this answer on Ray's forum too. Regards, Fred

提交回复
热议问题