您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 7:實作 UIAlertView 並監聽按鈕點擊事件

編輯:iOS 相關資訊

UIAlertView 是 iOS 早期常用的彈窗提示元件。以下示範如何以「預設樣式」建立一個提示框,並監聽使用者點擊不同按鈕的事件。

步驟一:遵循代理協議

在 view controller 的 .m 檔中宣告遵守 UIAlertViewDelegate:

@interface moboViewController () <UIAlertViewDelegate>
@end

步驟二:在 viewDidLoad 中建立並顯示

- (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 取代並逐步弃用,新專案建議改用後者。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved