Objective-C-UIAlertView不委托

时间:2018-08-10 09:59:59

标签: ios objective-c uialertview

我有这段代码,我试图在警报视图上获取语言选择器,但我认为该委托无法正常工作。

@interface JumboEntranceViewController () <FBSDKLoginButtonDelegate, WSLoginDelegate, UIAlertViewDelegate, UITextFieldDelegate>
...
...
...
...

- (void) showLanguageSelector {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Idioma" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"English",@"Español",@"Deustch", nil];
    alert.delegate = self;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 0) { //CANCEL
        [[LanguagesManager sharedInstance] setLanguage:@"es"];
    }
    else if(buttonIndex == 1) {
        [[LanguagesManager sharedInstance] setLanguage:@"en"];
    }
    else if(buttonIndex == 2) {
        [[LanguagesManager sharedInstance] setLanguage:@"es"];
    }
    else if (buttonIndex == 3) {
        [[LanguagesManager sharedInstance] setLanguage:@"de"];
    }
}

但是我不能进入函数 didDismissWithButtonIndex

2 个答案:

答案 0 :(得分:2)

使用此代码。 (从iOS 9.0开始不推荐使用UIAlertView。)

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Idioma" message:@"" preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:@"English" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[LanguagesManager sharedInstance] setLanguage:@"en"];
    }]];

    [alert addAction:[UIAlertAction actionWithTitle:@"Español" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[LanguagesManager sharedInstance] setLanguage:@"es"];
    }]];

    [alert addAction:[UIAlertAction actionWithTitle:@"Deustch" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[LanguagesManager sharedInstance] setLanguage:@"de"];
    }]];

    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [[LanguagesManager sharedInstance] setLanguage:@"es"];
    }]];

    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alert animated:YES completion:nil];

答案 1 :(得分:-1)

首先,如注释中所述,自iOS 9.0起不推荐使用UIAlertView。您应该改用UIAlertController,就像Xcode在执行UIAlertView和委托方法时都通过警告告诉您

无论如何,我实现了代码的精确副本,并且可以正常工作:您确定问题不在LanguageManager单例中吗?您是否尝试过将断点放在alertview:didDismissWithButtonIndex:的第一行中,以查看是否被调用?

[edit]为了澄清,下面是代码and here's the proof it works

import time


def profile(function):
    def wrapper(*args):
        start_time = time.time()
        function(*args)
        end_time = time.time()
        function.time_taken = end_time-start_time
        return exec_time
    return wrapper

"""
@profile
def calsqr(a,b):
    return a**b
"""
@profile
def expensive_operation():
   import time
   time.sleep(3)
   return 1


print(expensive_operation.time_taken)
assert expensive_operation() == 1