View frame changes between viewWillAppear: and viewDidAppear:

前端 未结 4 1911
慢半拍i
慢半拍i 2020-11-28 22:57

I have discovered a strange behavior in my application, where a connected IBOutlet has its connected view\'s frame between the calls in my view controller to

相关标签:
4条回答
  • 2020-11-28 23:31

    call

    self.scrollView.layoutIfNeeded()

    in your viewWillAppear method. Afterwards you can access it's frame and it will have the same value as you print in viewDidAppear

    0 讨论(0)
  • 2020-11-28 23:41

    From the documentation:

    viewWillAppear:
    

    Notifies the view controller that its view is about to be added to a view hierarchy.

    viewDidAppear:
    

    Notifies the view controller that its view was added to a view hierarchy.

    As a result the frames of the subviews aren't yet set in the viewWillAppear:

    The appropriate method to modify your UI before the view is presented to the screen is:

    viewDidLayoutSubviews
    

    Notifies the view controller that its view just laid out its subviews.

    0 讨论(0)
  • 2020-11-28 23:44

    Autolayout made a huge change in how we design and develop the GUI of our views. One of the main differences is that autolayout doesn't change our view sizes immediately, but only when is triggered, that means at a specific time, but we can force it to recalculate our constraints immediately or mark them as "in need" of layout. It works like -setNeedDisplay.
    The big challenge for me was to understand and accept that, we do not need to use autoresizing masks anymore, and frame has become a useless property in placing our views. We do not need to think about view position anymore, but we should think how we want to see them in a space related to each other.
    When we want to mix old autoresizing mask and autolayout is when problems arise. We should think about autolayout implementation really soon and try to avoid to mix the old approach in a view hierarchy based on autolayout.
    Is fine to have a container view that uses only autoresizing masks, such as a main view of a view controller, but is better if we do not try to mix.
    I never used storyboard, but most proably it is correct. Using Autolayout, frame of your views are set when the autolayout engine starts its calculation. Try to ask the same thing right after super of - (void)viewDidLayoutSubviews method of your view controller.
    This method is called when the autolayout engine has finished to calculate your views' frames.

    0 讨论(0)
  • 2020-11-28 23:47

    In my case, moving all frame related methods to

    override func viewWillLayoutSubviews()
    

    worked perfectly(I was trying to modify constraints from storyboard).

    0 讨论(0)
提交回复
热议问题