How to present UIAlertController when not in a view controller?

前端 未结 30 3128
庸人自扰
庸人自扰 2020-11-22 06:21

Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method call

30条回答
  •  粉色の甜心
    2020-11-22 07:16

    Seems to work:

    static UIViewController *viewControllerForView(UIView *view) {
        UIResponder *responder = view;
        do {
            responder = [responder nextResponder];
        }
        while (responder && ![responder isKindOfClass:[UIViewController class]]);
        return (UIViewController *)responder;
    }
    
    -(void)showActionSheet {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Do it" style:UIAlertActionStyleDefault handler:nil]];
        [viewControllerForView(self) presentViewController:alertController animated:YES completion:nil];
    }
    

提交回复
热议问题