How do run some code when an UIView is loaded on iOS?
I want to run some code when any UIView is loaded from the resources.
How can I do that, without having to modify implementation of each UIView subclass?
Note: subclassing UIVi开发者_如何转开发ew is not an option.
You should subclass UIView and then use your subclass for all your others UIviews
You could consider creating a UIView
, which will be the base view class to all your UIView
as suggested by @gsempe and implement the willMoveToSuperview:
method.
From Documentation.
Tells the view that its superview is about to change to the specified superview.
- (void)willMoveToSuperview:(UIView *)newSuperview;
- (void)willMoveToWindow:(UIWindow *)newWindow;
Since we are talking resources and NIB implicitly, I can recollect only two methods in which you would load a view – UIViewController
's initWithNibName:bundle
or loadNibNamed:owner:options:
although there might be some private methods that we aren't provided access to.
So you can think of overriding behavior there. You can create a custom UIViewController
subclass that will be the parent for all your view controller's and subclass NSBundle
to override loadNibNamed:owner:options:
. But this might depend on what kind of task you want to accomplish.
You can try declaring your own category and override a method, but I don't think that would be a good practice. Other way is to extend the UIView subclass and override the method you want. And use that class in your application instead of UIView.
So the approach really depends on your use case.
精彩评论