设置UIAlertView的委托

时间:2014-11-11 21:39:47

标签: ios objective-c delegates

我正在更新新UIAlertController的代码,因为整个项目中有很多警报,我将警报代码拉到了自己的类中。 UIAlertController效果很好,但我无法让旧UIAlertView工作。

如果我使用 self 作为委托,则代码崩溃。我怀疑因为在调用委托时对象已经消失了。如果我使用self.navigationController,代码不会崩溃,但委托不会点击按钮。我在调用类中有相同的委托方法,也没有被调用。

我尝试将showAlert方法设为类方法,但这不起作用。我怀疑我可能需要将UIAlertView委托设置为调用类,但不知道该怎么做。

@implementation ShowSystemAlert
- (instancetype)initWithNavigatioController:(UINavigationController *)navigationController
                   withManagedObjectContext:(NSManagedObjectContext *)context
                            withScoreKeeper:(ScoreKeeper *)scoreKeeper
                               withWordList:(WordList *)wordlist {

    self = [super init];
    if (self) {
        _navigationController = navigationController;
        _mObjContext = context;
        _scoreKeeper = scoreKeeper;
        _wordList = wordlist;
    }

    return self;
}

- (void)showAlert {

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {

        // code for UIAlertController goes here

        [self.navigationController presentViewController:alert animated:true completion:nil];

    } else {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"'Only Show Favorites'\nTurned Off"
                                                    message:@"aWe looked for words in the categories you selected but did not find any. We turned off 'Only Show Favorites' and found some words."
                                                   self.navigationController
                                          cancelButtonTitle:@"Settings"
                                          otherButtonTitles:@"Continue", nil];

        [alert show];
    }
}

#pragma mark - No Words

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"In alertView delegate");
    if (buttonIndex == 0) {
        NSLog(@"Cancel buttonpressed on no words");
        PrefsTableViewController *ptvc = [[PrefsTableViewController alloc]
                                          initWithWordList:self.wordList];
        [self.navigationController pushViewController:ptvc animated:YES];

    }
}

@end

2 个答案:

答案 0 :(得分:0)

@interface ShowSystemAlert:UIViewController <UIAlertViewDelegate> // The delegate needs to be added to the class that will listen to the delegate. Generally the viewController.

// In your method where you create your alertView assign the delegate
alert.delegate = self;

答案 1 :(得分:0)

在iOS8下,请将您的委托方法clickedButtonAtIndex更改为didDismissWithButtonIndex

将此行更改为

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

用这个

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 

您应该会发现这将解决崩溃。

我希望这会有所帮助。