共用方式為


在 Xamarin.iOS 中顯示警示

從 iOS 8 開始,UIAlertController 已完成取代的 UIActionSheet 和 UIAlertView,這兩者現在都已被取代。

不同於它所取代的類別,這些類別是UIView的子類別,UIAlertController是UIViewController的子類別。

用來 UIAlertControllerStyle 指出要顯示的警示類型。 這些警示類型如下:

  • UIAlertControllerStyleActionSheet
    • iOS 8 之前,這會是UIActionSheet
  • UIAlertControllerStyleAlert
    • iOS 8 之前,這會是 UIAlertView

建立警示控制器時,需要採取三個必要步驟:

  • 使用下列專案建立及設定警示:

    • title
    • message
    • preferredStyle
  • (選擇性)新增文字欄位

  • 新增必要動作

  • 呈現檢視控制器

最簡單的警示包含單一按鈕,如下列螢幕快照所示:

具有一個按鈕的警示

顯示簡單警示的程式代碼如下所示:

okayButton.TouchUpInside += (sender, e) => {

    //Create Alert
    var okAlertController = UIAlertController.Create ("Title", "The message", UIAlertControllerStyle.Alert);

    //Add Action
    okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null));

    // Present Alert
    PresentViewController (okAlertController, true, null);
};

以類似的方式顯示具有多個選項的警示,但新增兩個動作。 例如,下列螢幕快照顯示具有兩個按鈕的警示:

具有兩個按鈕的警示

okayCancelButton.TouchUpInside += ((sender, e) => {

    //Create Alert
    var okCancelAlertController = UIAlertController.Create("Alert Title", "Choose from two buttons", UIAlertControllerStyle.Alert);

    //Add Actions
    okCancelAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, alert => Console.WriteLine ("Okay was clicked")));
    okCancelAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine ("Cancel was clicked")));

    //Present Alert
    PresentViewController(okCancelAlertController, true, null);
});

警示也可以顯示動作表,如下所示的螢幕快照:

動作表單警示

按鈕會使用 AddAction 方法新增至警示:

actionSheetButton.TouchUpInside += ((sender, e) => {

    // Create a new Alert Controller
    UIAlertController actionSheetAlert = UIAlertController.Create("Action Sheet", "Select an item from below", UIAlertControllerStyle.ActionSheet);

    // Add Actions
    actionSheetAlert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default, (action) => Console.WriteLine ("Item One pressed.")));

    actionSheetAlert.AddAction(UIAlertAction.Create("custom button 1",UIAlertActionStyle.Default, (action) => Console.WriteLine ("Item Two pressed.")));

    actionSheetAlert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel, (action) => Console.WriteLine ("Cancel button pressed.")));

    // Required for iPad - You must specify a source for the Action Sheet since it is
    // displayed as a popover
    UIPopoverPresentationController presentationPopover = actionSheetAlert.PopoverPresentationController;
    if (presentationPopover!=null) {
        presentationPopover.SourceView = this.View;
        presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
    }

    // Display the alert
    this.PresentViewController(actionSheetAlert,true,null);
});