UIAlertView的类别需要回调警报按钮单击iOS



我的场景如下

1(我为UIAlertView类创建了一个Category

//UIAlertView+Remove.m file
#import "UIAlertView+Remove.h"
@implementation UIAlertView (Remove)
- (void) hide {
    [self dismissWithClickedButtonIndex:0 animated:YES];
}
- (void)removeNotificationObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
}
@end

2(在 UIAlertView 对象显示时向其添加了通知

3(我想在用户时调用removeNotificationObserver方法 单击警报视图中的任意按钮以删除通知观察程序。

我试过的西涅里奥斯

  • 此处无法从委托调用- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex因为委托未正确设置为所有警报视图对象。

  • 从类别中的-dealloc方法调用它,但在警报视图关闭时未触发-dealloc

谁能帮我度过难关?

UIAlertView自iOS8以来已被弃用,所以我建议你不要再使用它,而不是你可以使用UIAlertController,如下所示,它可以在不使用任何委托方法的情况下执行按钮的操作。

UIAlertController *alertController = [UIAlertController
alertControllerWithTitle: @"Title" message:@"Message" preferredStyle: UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle: @"OK" style: UIAlertActionStyleDefault handler: ^(UIAlertAction *action)
                                   {  
                                   }];
[alertController addAction: OKAction];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle: @"cancel" style: UIAlertActionStyleDefault handler: ^(UIAlertAction *action)
                                   { 
                                   }];
[alertController addAction: cancelAction];
[self presentViewController:alertController animated:YES completion:nil];

感谢您的回复!

最后,我自己通过实现 UIAlertView 的子类而不是使用 Category 来解决它。在这里我评论了我的代码片段,对于那些遇到相同问题的人可能会有所帮助

//UIAlertView_AutoClose.m file
#import "UIAlertView_AutoClose.h"
@implementation UIAlertView_AutoClose
- (id)initWithTitle:(NSString *)title
            message:(NSString *)message
           delegate:(id)delegate
  cancelButtonTitle:(NSString *)cancelButtonTitle
  otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    if(delegate == nil){
        delegate = self;
    }
    return [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
    NSLog(@"Reached alertview_autoclose");
}
- (void) hide {
    [self dismissWithClickedButtonIndex:0 animated:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
}
@end

最新更新