UIView did appear?

2019-03-17 14:23发布

问题:

I'm wondering, is there a way to get a delegate or something, when a particular UIView has been shown on the screen ?

回答1:

Try these:

– didAddSubview:
– willRemoveSubview:
– willMoveToSuperview:
– didMoveToSuperview
– willMoveToWindow:
– didMoveToWindow
- viewDidAppear:


回答2:

If you manage your logic directly inside the UIView, use:

- didMoveToSuperview

If you manage your logic inside a UIViewController, use :

- viewDidAppear:(BOOL)animated


回答3:

Swift version. Inside your UIView class just:

override func willMove(toWindow newWindow: UIWindow?) {
    super.willMove(toWindow: newWindow)

    if newWindow == nil {
        // UIView disappear
    } else {
        // UIView appear
    }
}


回答4:

If you are managing the UIView via a UIViewController, then you can use the -viewDidAppear: method:

- (void) viewDidAppear:(BOOL) animated {
   //do stuff...
   [super viewDidAppear:animated];
}


回答5:

Another way to find out when a control is on screen is to subclass the View or Control and override drawRect... However, it's called when it's drawn and not only when first shown. So it's only sometimes what you want. It worked for my case. Make sure to call super as well! =)