Search code examples
iosuiviewuiactionsheetappdelegateuiwindow

Find top shown view UIActionSheet


I have the following code that displays an action sheet over the the current visible view (self.view)

[actionSheet showInView:[self view]];

But I'am unable to get a reference to this action sheet in the app delegate by using:

UIView *topView = [[self.window subviews] lastObject];

Solution

  • I believe that the action sheet is not really added as a subview:

    - (void)didPresentActionSheet:(UIActionSheet *)actionSheet
    {
        NSLog(@"%@, %@", actionSheet.superview, self.view);
    }
    

    So one of the ways would be to have a notification posted when the action sheet is displayed; for example:

    // delegate = self;
    - (void)didPresentActionSheet:(UIActionSheet *)actionSheet
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ActionSheetPresented" object:nil userInfo:@{@"actionSheet": actionSheet}];
    }
    

    And add an observer for the notification in the AppDelegate

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayed:) name:@"ActionSheetPresented" object:nil];
    
    - (void)displayed:(NSNotification *)notification
    {
        UIActionSheet *action = notification.userInfo[@"sheet"];
        NSLog(@"%@", action);
    }
    

    You might also just leave it is a public property in the view controller and reference in the AppDelegate whenever there is didPresentActionSheet: delegate API fires.