iOS viewDidLoad for UIView

In a ViewController, there is ViewDidLoad to know when the VC has loaded.

For a UIView, what method do i have to use when the view loaded?

Would this method be called with any init?

edit: No XIB, just programmatically.


If you load it from a XIB file, the awakeFromNib method will be called once loading finishes:

override public func awakeFromNib() {
    super.awakeFromNib();

    // ... loading logic here ...
}

Update; In the case of no XIB, you will probably have to infer it using one of the methods from the Observing View-Related Changes area of the docs (for example, didMoveToSuperview). However, a better way is to send a message to your views from the view controller's viewDidLoad method if possible.


You can use willMove(toSuperview newSuperview: UIView?)

import UIKit

final class myView: UIView {

  override func willMove(toSuperview newSuperview: UIView?) {
     super.willMove(toSuperview: newSuperview)
     //Do stuff here
   }

} 

Apple Docs


Actualy, you have not to do anything with view controller's method viewDidLoad(), for your view's initialization. All that you want to do, you can do in view's init method. For example, in view controller's viewDidLoad(), there is some initialization code:

- (void)viewDidLoad{
    [super viewDidLoad];

    // init your parameters here
}

Analogously, in your view's init method:

- (id)initWithDelegate:(id)_delegate
{
    self = [[[[NSBundle mainBundle] loadNibNamed:@"YourView" owner:self options:nil] objectAtIndex:0] retain];
    if (self) {
        [super init];

        self.delegate = _delegate;

        // init your parameters here

        return self;

    }
    return nil;
}

Then, you create YourView from view controller like this:

YourView view = [[YourView alloc] initWithDelegate:self];
[self.view addSubview:view];
[view release];

Further, things that you want to do when your view did load, you can place in layoutSubviews method in your view, like this:

-(void)layoutSubviews{
    [super layoutSubviews];

    // init your parameters here, like set up fonts, colors, etc...
}

I think, that is what you need.

Cheers!


Swift 2:

import UIKit

class myView: UIView {

  override func layoutSubviews() {
    print("run when UIView appears on screen")
    // you can update your label's text or etc.
  }
}