共用方式為


在 Xamarin 中使用 tvOS 警示

本文涵蓋使用UIAlertController,在 Xamarin.tvOS 中向用戶顯示警示訊息。

如果您需要引起 tvOS 使用者的注意,或要求許可權執行破壞性動作(例如刪除檔案),您可以使用 來顯示警示訊息 UIAlertViewController

UIAlertViewController 範例

如果除了顯示訊息之外,您還可以將按鈕和文字欄位新增至警示,讓用戶回應動作並提供意見反應。

關於警示

如上所述,警示可用來引起使用者的注意,並通知他們您的應用程式狀態或要求意見反應。 警示必須呈現標題,他們可以選擇性地擁有訊息和一或多個按鈕或文字欄位。

範例警示

Apple 有下列使用警示的建議:

  • 謹慎使用警示 - 警示會中斷應用程式的使用者流程,並中斷用戶體驗,因此,應該只用於錯誤通知、應用程式內購買和破壞性動作等重要情況。
  • 提供有用的選擇 - 如果警示向用戶呈現選項,則您應該確保每個選項都提供重要資訊,併為用戶採取有用的動作。

警示標題和訊息

Apple 有下列建議來呈現警示的標題和選擇性訊息:

  • 使用多字標題 - 警示的標題 應該清楚取得情況的點,同時仍然保持簡單。 單字標題很少提供足夠的資訊。
  • 使用不需要訊息 的描述性標題 - 可能的話,請考慮讓警示的標題描述性足夠,而不需要選擇性的訊息文字。
  • 將訊息設為簡短、完整句子 - 如果需要選擇性的訊息來取得警示的點,請盡可能保持簡單,並使它成為具有適當大寫和標點符號的完整句子。

警示按鈕

Apple 有下列將按鈕新增至警示的建議:

  • 限制為兩個按鈕 - 盡可能將警示限制為最多兩個按鈕。 單一按鈕警示提供資訊,但沒有動作。 兩個按鈕警示提供簡單的是/沒有選擇的動作。
  • 使用簡潔的邏輯按鈕標題 - 簡單一到兩個單字按鈕標題 ,清楚描述按鈕的動作效果最好。 如需詳細資訊,請參閱使用 按鈕 檔。
  • 清楚標示破壞性按鈕 - 對於執行破壞性動作的按鈕 ,[例如刪除檔案] 會以樣式清楚地標示它們 UIAlertActionStyle.Destructive

顯示警示

若要顯示警示,您可以建立的 UIAlertViewController 實例,並藉由新增 [動作] [按鈕] 並選取 [警示] 的樣式加以設定。 例如,下列程式代碼會顯示 [確定/取消] 警示:

const string title = "A Short Title is Best";
const string message = "A message should be a short, complete sentence.";
const string acceptButtonTitle = "OK";
const string cancelButtonTitle = "Cancel";
const string deleteButtonTitle = "Delete";
...

var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);

// Create the action.
var acceptAction = UIAlertAction.Create (acceptButtonTitle, UIAlertActionStyle.Default, _ =>
    Console.WriteLine ("The \"OK/Cancel\" alert's other action occurred.")
);

var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, _ =>
    Console.WriteLine ("The \"OK/Cancel\" alert's other action occurred.")
);

// Add the actions.
alertController.AddAction (acceptAction);
alertController.AddAction (cancelAction);
PresentViewController (alertController, true, null);

讓我們詳細查看此程序代碼。 首先,我們會使用指定的標題和訊息建立新的警示:

UIAlertController.Create (title, message, UIAlertControllerStyle.Alert)

接下來,針對我們想要在警示中顯示的每個按鈕,我們會建立定義按鈕標題的動作、其樣式,以及按下按鈕時所要採取的動作:

UIAlertAction.Create ("Button Title", UIAlertActionStyle.Default, _ =>
    // Do something when the button is pressed
    ...
);

列舉 UIAlertActionStyle 可讓您將按鈕的樣式設定為下列其中一項:

  • 預設值 - 按鈕將是顯示警示時選取的預設按鈕。
  • 取消 - 按鈕是警示的取消按鈕。
  • 破壞性 - 醒目提示按鈕作為破壞性動作,例如刪除檔案。 目前,tvOS 會以紅色背景呈現破壞性按鈕。

方法 AddAction 會將指定的動作新增至 , UIAlertViewController 最後 PresentViewController (alertController, true, null) 方法會向用戶顯示指定的警示。

新增文字欄位

除了將動作(按鈕)新增至警示之外,您還可以將文字欄位新增至警示,讓使用者填入使用者標識碼和密碼等資訊:

警示中的文字欄位

如果使用者選取 [文字字段],則會顯示標準 tvOS 鍵盤,讓他們輸入字段的值:

輸入文字

下列程式代碼會顯示 [確定/取消警示],其中含有單一文字欄位來輸入值:

UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert);
UITextField field = null;

// Add and configure text field
alert.AddTextField ((textField) => {
    // Save the field
    field = textField;

    // Initialize field
    field.Placeholder = placeholder;
    field.Text = text;
    field.AutocorrectionType = UITextAutocorrectionType.No;
    field.KeyboardType = UIKeyboardType.Default;
    field.ReturnKeyType = UIReturnKeyType.Done;
    field.ClearButtonMode = UITextFieldViewMode.WhileEditing;

});

// Add cancel button
alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => {
    // User canceled, do something
    ...
}));

// Add ok button
alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => {
    // User selected ok, do something
    ...
}));

// Display the alert
controller.PresentViewController(alert,true,null);

方法會將 AddTextField 新的文字欄位元新增至警示,您可以設定佔位元文字等屬性,例如佔位元文字(欄位空白時出現的文字)、默認文字值和鍵盤類型。 例如:

// Initialize field
field.Placeholder = placeholder;
field.Text = text;
field.AutocorrectionType = UITextAutocorrectionType.No;
field.KeyboardType = UIKeyboardType.Default;
field.ReturnKeyType = UIReturnKeyType.Done;
field.ClearButtonMode = UITextFieldViewMode.WhileEditing;

因此,我們稍後可以處理文字欄位的值,我們也會使用下列程式代碼來儲存 的復本:

UITextField field = null;
...

// Add and configure text field
alert.AddTextField ((textField) => {
    // Save the field
    field = textField;
    ...
});

當使用者在 [文字字段] 中輸入值之後,我們可以使用 field 變數來存取該值。

警示檢視控制器協助程序類別

因為使用 UIAlertViewController 顯示簡單、常見的警示類型可能會導致相當多的程式代碼重複,所以您可以使用協助程式類別來減少重複的程式碼數量。 例如:

using System;
using Foundation;
using UIKit;
using System.CodeDom.Compiler;

namespace UIKit
{
    /// <summary>
    /// Alert view controller is a reusable helper class that makes working with <c>UIAlertViewController</c> alerts
    /// easier in a tvOS app.
    /// </summary>
    public class AlertViewController
    {
        #region Static Methods
        public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) {
            // No, inform the user that they must create a home first
            UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert);

            // Configure the alert
            alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {}));

            // Display the alert
            controller.PresentViewController(alert,true,null);

            // Return created controller
            return alert;
        }

        public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) {
            // No, inform the user that they must create a home first
            UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert);

            // Add cancel button
            alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => {
                // Any action?
                if (action!=null) {
                    action(false);
                }
            }));

            // Add ok button
            alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => {
                // Any action?
                if (action!=null) {
                    action(true);
                }
            }));

            // Display the alert
            controller.PresentViewController(alert,true,null);

            // Return created controller
            return alert;
        }

        public static UIAlertController PresentDestructiveAlert(string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) {
            // No, inform the user that they must create a home first
            UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert);

            // Add cancel button
            alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => {
                // Any action?
                if (action!=null) {
                    action(false);
                }
            }));

            // Add ok button
            alert.AddAction(UIAlertAction.Create(destructiveAction,UIAlertActionStyle.Destructive,(actionOK) => {
                // Any action?
                if (action!=null) {
                    action(true);
                }
            }));

            // Display the alert
            controller.PresentViewController(alert,true,null);

            // Return created controller
            return alert;
        }

        public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) {
            // No, inform the user that they must create a home first
            UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert);
            UITextField field = null;

            // Add and configure text field
            alert.AddTextField ((textField) => {
                // Save the field
                field = textField;

                // Initialize field
                field.Placeholder = placeholder;
                field.Text = text;
                field.AutocorrectionType = UITextAutocorrectionType.No;
                field.KeyboardType = UIKeyboardType.Default;
                field.ReturnKeyType = UIReturnKeyType.Done;
                field.ClearButtonMode = UITextFieldViewMode.WhileEditing;

            });

            // Add cancel button
            alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => {
                // Any action?
                if (action!=null) {
                    action(false,"");
                }
            }));

            // Add ok button
            alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => {
                // Any action?
                if (action!=null && field !=null) {
                    action(true, field.Text);
                }
            }));

            // Display the alert
            controller.PresentViewController(alert,true,null);

            // Return created controller
            return alert;
        }
        #endregion

        #region Delegates
        public delegate void AlertOKCancelDelegate(bool OK);
        public delegate void AlertTextInputDelegate(bool OK, string text);
        #endregion
    }
}

使用這個類別,即可顯示和響應簡單的警示,如下所示:

#region Custom Actions
partial void DisplayDestructiveAlert (Foundation.NSObject sender) {
    // User helper class to present alert
    AlertViewController.PresentDestructiveAlert("A Short Title is Best","The message should be a short, complete sentence.","Delete",this, (ok) => {
        Console.WriteLine("Destructive Alert: The user selected {0}",ok);
    });
}

partial void DisplayOkCancelAlert (Foundation.NSObject sender) {
    // User helper class to present alert
    AlertViewController.PresentOKCancelAlert("A Short Title is Best","The message should be a short, complete sentence.",this, (ok) => {
        Console.WriteLine("OK/Cancel Alert: The user selected {0}",ok);
    });
}

partial void DisplaySimpleAlert (Foundation.NSObject sender) {
    // User helper class to present alert
    AlertViewController.PresentOKAlert("A Short Title is Best","The message should be a short, complete sentence.",this);
}

partial void DisplayTextInputAlert (Foundation.NSObject sender) {
    // User helper class to present alert
    AlertViewController.PresentTextInputAlert("A Short Title is Best","The message should be a short, complete sentence.","placeholder", "", this, (ok, text) => {
        Console.WriteLine("Text Input Alert: The user selected {0} and entered `{1}`",ok,text);
    });
}
#endregion

摘要

本文涵蓋在 UIAlertController Xamarin.tvOS 中向用戶顯示警示訊息。 首先,它示範如何顯示簡單的警示並新增按鈕。 接下來,它示範如何將文字欄位新增至警示。 最後,它示範如何使用協助程序類別來減少顯示警示所需的重複程式代碼數量。