Unable to set frame correctly before viewDidAppear

后端 未结 3 1401
悲&欢浪女
悲&欢浪女 2020-11-30 22:45

I was wondering if anyone knows why when you set the frame of a subview in viewDidLoad and viewWillAppear the changes do not take affect on the scr

相关标签:
3条回答
  • 2020-11-30 23:10

    in viewWillAppear()

    just call layoutIfNeeded() once for the view whose frame you want to get.

    if tableView then tableView.layoutIfNeeded() for exmple

    0 讨论(0)
  • 2020-11-30 23:12

    See this thread When is layoutSubviews called?
    When use autolayout, framework do not call layoutSubviews automatically. That is very important. From ref:

    • init does not cause layoutSubviews to be called (duh)
    • addSubview: causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target. ...


    If you add subview in viewDidLoad, layoutSubviews called before viewDidAppear, and you can get the correct size of subviews. But if you do nothing, layoutSubviews will be called after viewDidAppear. It's up to your code.

    0 讨论(0)
  • 2020-11-30 23:15

    viewDidLoad is called when the class is loaded however no ui elements have been initialised and therefore any attempt to reference them will be overwritten or unavaliable during the initialisation process which happens between the viewDidLoad and viewDidAppear calls. Once all ui element have been initalised and drawn viewDidAppear is called.

    viewDidLoad - Called after the controller's view is loaded into memory

    At this point the view isn't within the view hierarchy.

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

    Again, the view is yet to be added to the view hierarchy.

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

    Only then is the view added to the view hierarchy.

    Update

    The viewDidLayoutSubviews is the most appropriate place to modify the UI before it actually appears on the screen.

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

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