iPhone: viewWillAppear is not called for UIView
I have created an UIView in my iPhone app. I want to handle something when user closes or opens when UIView is present as current screen. I thought, i can do this under viewWillAppear:
. But, viewWillAppear:
is no开发者_开发百科t called in UIView. Does it work only on UIViewController? How can i handle viewWillAppear:
or viewDidAppear:
for an UIView?
Update: UIView what I created everything through program, not in .xib.
Please advise.
Thanks!
From your message I infer that you wrote your viewWillAppear:
method on the UIView
class. As you suspect, that method is part of [UIViewController]
1, not [UIView]
2 therefore it only gets called on the UIViewController
.
You should connect the property view of the UIViewController
to the UIView
object in the interface builder and then implement that method in the UIViewController
.
If your view is created in response to an user action,
Update for your update:
You should tag the views either in code (view.tag=1
) or IB.
Then you can do if (self.window.rootViewController.view.tag == 1) { ... }
from your delegate (assuming you are looking for the view of the controller who is the rootController, otherwise post more details).
It's even better if you define constants on one place instead writing 1
as a literal.
These delegate methods are called every time the superview is presented to the screen and should be implemented in the UIViewControllers.
The gotcha is that these methods aren't called when subviews are presented on the screen, so your superview-view-controller will have to respond to these events accordingly.
You can find more information in this post here.
If you study the documentation for UIView
and UIViewController
what you will find is -(void)viewWillAppear:animated:
is a method of UIViewController
and not of UIView
, so in order to use it, it must be implemented by subclassing UIViewController
. Generally for best practice if you want to follow MVC, any functionality that does not pertain to the view itself should be delegated to the view controller and not be in the body of your UIView
subclass.
Create a new view controller with xib file, and then link your custom view class to the view in your xib file.
精彩评论