您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

同時相容 iOS 7 與 iOS 8 的 Alert 訊息提醒框

編輯:iOS 7 技巧

alert 是我們在 PC 上手邊最常見、最簡單的網頁提醒指令。下面我們就來做一個能同時在 iOS 7 與 iOS 8 上運作的 alert 訊息提醒框。

廢話不多說,直接看程式碼與註解:

    if respondsToSelector("UIAlertController"){
        var refreshAlert = UIAlertController(title: "注意", message: "確定要刪除該資訊嗎?", preferredStyle: UIAlertControllerStyle.Alert)
        refreshAlert.addAction(UIAlertAction(title: "是", style: .Default, handler:
            { (action: UIAlertAction!) in
             //實際程式碼
            }
            ))
        refreshAlert.addAction(UIAlertAction(title: "否", style: .Default, handler: nil))
        presentViewController(refreshAlert, animated: true, completion: nil)
    }
    else {
        let at = UIAlertView()
        at.delegate = self
        at.title = "注意"
        at.message = "確定要刪除該資訊嗎?"
        at.addButtonWithTitle("是")
        at.addButtonWithTitle("否")
        at.show()
    }

上面的程式碼在 iOS 8 下直接使用 UIAlertController,iOS 7 則使用 UIAlertView。iOS 8 的處理函式直接寫在 action 的 handler 中,而 iOS 7 則需實作代理函式:

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
    switch buttonIndex{
    case 0:
        //實際程式碼(選擇是)
        break;
    case 1:
        //實際程式碼(選擇否)
        break;
    default:
        break;
    }
}

這段程式碼我在手機上實測過,可用!

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