How to dismiss UIActionSheets and UIPopoverControl

2019-05-10 15:38发布

问题:

In my client application I have an idle timeout control mechanism and when the user does not do anything with the app for a specified time interval, I display a warning and throw him back to the login screen. This control happens in my container view where I initiate all of my other views. When the idle time is up, I pop this container view to its caller, i.e the login screen.

The problem is, if the user does sthg that displays an action sheet or a popover and then does not do anything until the idle time is up, when I throw him to the login screen the action sheets and the popovers also remain on the login screen since I don't dismiss them.

To solve this, I can think of making all the action sheets and the popovers retained members of my view controllers and then dismissing them on the viewWillDisappear methods of their owners. But I have so many view controllers, so I'm looking for other ways, if there are any.

So, the question is how can I make all these action sheets and popovers go away from my login screen without knowing who their callers are?

回答1:

I would register the UIPopover instance to listen to some notification.

[[NSNotificationCenter defaultCenter] addObserver:_myPopOver 
                                         selector:@selector(myDismissPopover)
                                             name:@"dismissPopover" 
                                           object:nil];

And add extension to UIPopover class.

- (void) myDismissPopover {
 [self dismissPopoverAnimated:YES];
}

When I need to dismiss popover, I just need to post notification.

[[NSNotificationCenter defaultCenter] postNotificationName:@"dismissPopover" 
                                                    object:nil];


回答2:

I'll write down my own solution as we've talked with bshirley in the comments of the question. I've implemented a mechanism like this to solve the problem:

In my login view controller, I create an NSMutableArray that will keep all my action sheets and popover controllers that are going to be dismissed. Then I store this array in a global dictionary. I access this dictionary via a utility method. Then all through the application, whoever creates an action sheet or a popover controller, adds the component to this array (retrieves the array from the global data, modifies it and then saves it back to the global data). Then when the user is thrown back to the login screen, in viewWillDisappear of my login view controller, I loop through this array and call the appropriate dismiss method by checking if the UIView I get from the array is an action sheet or a popover controller. Then I remove all the elements of this array and then store it back in the global data, again.

Hope this helps anyone who needs to implement a similar mechanism. Your comments will be appreciated.