2015-10-10 13 views
2

我開始學習Objective-C uikit,遇到一個問題.UIAlertViewDelegate沒有調用。誰能告訴我爲什麼?謝謝!Objective-C UIKit UIAlertViewDelegate不叫

#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 

回答

1

這是因爲您在更嚴格的使用期限內分配您的警報視圖,請嘗試將警報設置爲iVar或屬性,然後重試。

@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]; 

} 

並從showAlertTest方法中刪除定義。

P.S.:請注意,這種類型的顯示警報視圖在iOS 8以前不推薦使用,您應該使用UIAlertController代替,但如果出於任何原因您需要支持iOS 7及更低版本,那麼您應該爲警報制定一個強大的指針。

+0

非常感謝! –