UIAlertView 是 iOS 早期常用的彈窗提示元件。以下示範如何以「預設樣式」建立一個提示框,並監聽使用者點擊不同按鈕的事件。
在 view controller 的 .m 檔中宣告遵守 UIAlertViewDelegate:
@interface moboViewController () <UIAlertViewDelegate> @end
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 初始化 alertView
UIAlertView *altView = [[UIAlertView alloc]
initWithTitle:[self altTitle]
message:[self altMSG]
delegate:self
cancelButtonTitle:[self cancelBtnTitle]
otherButtonTitles:[self otherBtnTitle], nil];
// 2. 顯示
[altView show];
}
// 標題
- (NSString *)altTitle {
return @"下線通知";
}
// 訊息內容
- (NSString *)altMSG {
return @"你的帳號在異地登錄,密碼可能洩露,建議前往 https://mobodemy.com 進行修改。";
}
// 取消按鈕標題
- (NSString *)cancelBtnTitle {
return @"退出";
}
// 其他按鈕標題
- (NSString *)otherBtnTitle {
return @"重新登錄";
}
// 監聽點擊事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
if ([btnTitle isEqualToString:[self cancelBtnTitle]]) {
NSLog(@"你點擊了退出");
} else if ([btnTitle isEqualToString:[self otherBtnTitle]]) {
NSLog(@"你點擊了重新登錄按鈕");
}
}
透過 clickedButtonAtIndex: 這個 delegate 方法,就能依使用者所點的按鈕執行不同邏輯。補充一點:在 iOS 8 之後 UIAlertView 已被 UIAlertController 取代並逐步弃用,新專案建議改用後者。