简体   繁体   中英

Check which UIViewController my custom button class is on w/o Storyboard

I have created a custom class for my UIBarButtonItem ( refreshIndicator.m ). This button will be on many different view controllers, all push-segued from my MainViewController/NavigationController.

Instead of dragging an outlet onto every single ViewController.m file for iPhone storyboard THEN iPad storyboard (ugh, still targeting iOS7), I want to know if there is a way to complete my task simply within my UIBarButtonItem custom class. I've looked around everywhere but I haven't quite found an answer to this,

All I need to do is check which UIViewController is present, check the last time the page was refreshed, and then based on that time, set an image for the UIBarButtonItem. (I've got this part figured out though, unless someone has a better suggestion). How can I check for the current UIViewController within a custom button class? Is this possible?

Does it need to know which view controller its on so it can tell that vc it was pressed? If that's the case, then use your button's inherited target and action properties. On every vc that contains an instance of the button, in view did load:

self.myRefreshIndicator.target = self;
self.myRefreshIndicator.action = @selector(myRefreshIndicatorTapped:);

- (void)myRefreshIndicatorTapped:(id)sender {
    // do whatever
}

More generally, its better to have knowledge about the model flow to the views from the vc, and knowledge of user actions flow from the views. Under that principal, your custom button could have a method like:

- (void)timeIntervalSinceLastRefresh:(NSTimeInterval)seconds {
    // change how I look based on how many seconds are passed
}

And your vcs:

NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.lastRefreshDate];
[self.myRefreshIndicator timeIntervalSinceLastRefresh:interval];

If you really must go from a subview to a view controller, you could follow the responder chain as suggested in a few of the answers here (but I would go to great lengths to avoid this sort of thing).

It is possible to achieve this, but the solution is everything but elegant. It is one way of getting around the basic principles of iOS and is strongly discouraged.

One of the ways is to walk through the responder chain, posted by Phil M .

Another way is to look through all subviews of view controllers until you find the button.

Both ways are considered a bad practice and should be avoided.

For your particular case, I would rethink the structure of having a separate instance of the bar button. For example, you could rework it into a single UIButton instance that gets displayed over every view controller and it can also act as a singleton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM