I begin to learn Objective-C uikit , I ran into a problem.UIAlertViewDelegate not called.Can anyone tell me why? thank you!
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface AlertLearn : NSObject <UIAlertViewDelegate>
-(void) showAlertTest;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end
#import "AlertLearn.h"
#import <UIKit/UIKit.h>
@implementation AlertLearn
-(void) showAlertTest{
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"alert" message:@"alert test" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"clickedButtonAtIndex = %ld",buttonIndex );
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
NSLog(@"clickedButtonAtIndex title = %@",buttonTitle);
}
@end
This is because you are assigning your alert view in a stricter life span than it should be, try making your alert an iVar or property and try again.
@interface AlertLearn : NSObject <UIAlertViewDelegate>
{
UIAlertView * alertView;
}
-(void) showAlertTest;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end
...
-(void) showAlertTest{
alertView = [[UIAlertView alloc] initWithTitle:@"alert" message:@"alert test" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alertView show];
}
and remove the definition from your showAlertTest method.
P.S.: Please note that this type of showing alert view are deprecated as of iOS 8, you should use UIAlertController instead, but if for any reason you need to support iOS 7 and below, well, you should make a strong pointer for your alert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With