83

Is there anything similar to the viewDidLoad of UIViewController for a UIView??? I need to be notified as soon as a UIView has loaded (Subclass of UIView), and perform some actions.

1 Answer 1

277

Depending on what kind of actions you need to perform, there are several techniques:

  1. -(id)initWithFrame:(CGRect)frame - UIView's designated initializer; always sent to a UIView to initialize it, unless the view is loaded from a nib;
  2. -(id)initWithCoder:(NSCoder *)coder - always sent to initialize a UIView whenever the view is loaded from a nib;
  3. -(void)awakeFromNib - sent after all the objects in the nib are initialized and connected; applicable only if you load the object from a nib; you must call super;
  4. -(void)willMoveToSuperview:(UIView *)newSuperview - sent immediately before the view is added as a subview to another view; newSuperview may be nil when you remove the view from its superview;
  5. -(void)willMoveToWindow:(UIWindow *)newWindow - sent immediately before the view (or its superview) is added to a window; newWindow may be nil when you remove the view from a window;
  6. -(void)didMoveToSuperview - sent immediately after the view is inserted into a view hierarchy;
  7. -(void)didMoveToWindow - sent immediately after the view gets its window property set. -

Basically, you can choose to perform your actions during initialization (1 & 2), after loading from a nib (3), before insertion into a view hierarchy (4 & 5) and after that (6 & 7).

4
  • Thanks a lot perfect answer (very detailed). I was modifying a segmented control and it wasn't displaying the changes because I was calling the modification method during init, I moved it to didMoveToWindow and it fixed all the problems
    – aryaxt
    Dec 21, 2010 at 18:55
  • 1
    It seems all of this happened before viewDidLoad in viewController
    – Alex Chan
    Apr 17, 2015 at 8:53
  • 3
    -(void)willMoveToSuperview:(UIView *)newSuperview was the cure to all my problems, thank you very much!
    – Erion S
    Jul 15, 2015 at 15:05
  • I forgot again that some things do not work if you keep caling them inside a UIView at the very beginning of the initialization process..... So doing it in 7 or performing with delay from there will always work! :)
    – Alex Cio
    Dec 3, 2016 at 23:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.