Xamarin での tvOS アラートの操作

この記事では、UIAlertController を使用して、Xamarin.tvOS でユーザーにアラート メッセージを表示する方法について説明します。

tvOS ユーザーの注意を引く必要がある場合、または破壊的なアクション (ファイルの削除など) を実行するアクセス許可を求める必要がある場合は、UIAlertViewController を使用してアラート メッセージを表示できます。

UIAlertViewController の例

メッセージの表示に加えて、ボタンとテキスト フィールドをアラートに追加して、ユーザーがアクションに応答してフィードバックを提供できるようにします。

アラートの詳細

前述のように、アラートはユーザーの注意を引き、アプリの状態を通知したり、フィードバックを要求したりするために使用されます。 アラートはタイトルを提示する必要があります。必要に応じて、メッセージと 1 つ以上のボタンまたはテキスト フィールドを含めることができます。

アラートの例

Apple には、アラートの操作に関する次の推奨事項があります。

  • アラートを慎重に使用する - アラートによってアプリのフローが中断され、ユーザー エクスペリエンスが中断されます。そのため、エラー通知、アプリ内購入、破壊的アクションなどの重要な状況でのみ使用する必要があります。
  • 役に立つ選択肢を提供する - アラートがユーザーにオプションを提示する場合は、各オプションが重要な情報を提供し、ユーザーが実行するための有用なアクションが確実に提供されるようにする必要があります。

アラートのタイトルとメッセージ

Apple には、アラートのタイトルとオプションのメッセージを表示するための次の提案があります。

  • マルチワード タイトルを使用する - アラートのタイトルは、シンプルにしながら、状況のポイントを明確に把握できるようにする必要があります。 単語 1 つのタイトルで十分な情報が提供されることはほとんどありません。
  • メッセージを必要としない説明的なタイトルを使用する - 可能な限り、オプションのメッセージ テキストが必要にならない程度にアラートのタイトルをわかりやすいものにすることを検討してください。
  • メッセージを短く完全な文にする - アラートのポイントを把握するためにオプションのメッセージが必要な場合は、できるだけシンプルにし、大文字小文字の区別と句読点が適切に使用された完全な文にします。

アラート ボタン

Apple では、アラートにボタンを追加するために次のように提案しています。

  • 2 つのボタンに制限する - 可能な限り、アラートのボタンは最大 2 つに制限します。 ボタンが 1 つのアラートは情報は提供しますが、アクションは提供しません。 ボタンが 2 つのアラートは、単純な「はい」または「いいえ」を選択するアクションを提供します。
  • 簡潔で論理的なボタン タイトルを使用する - ボタン アクションの働きを最も明確に説明するシンプルな 1 から 2 単語のボタン タイトル。 詳細については、ボタンの操作に関するドキュメントを参照してください。
  • 破壊的なボタンを明確にマークする - 破壊的なアクション (ファイルの削除など) を実行するボタンは、UIAlertActionStyle.Destructive スタイルを使用して明確にマークします。

アラートの表示

アラートを表示するには、UIAlertViewController のインスタンスを作成し、アクション (ボタン) を追加し、アラートのスタイルを選択して構成します。 たとえば、次のコードでは、OK/キャンセル アラートが表示されます。

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 列挙型を使用すると、ボタンのスタイルを次のいずれかとして設定できます。

  • Default - このボタンは、アラートが表示されたときに選択された既定のボタンになります。
  • Cancel - このボタンは、アラートのキャンセル ボタンです。
  • Destructive - ファイルの削除など、破壊的なアクションとしてボタンを強調表示します。 現在、tvOS では、Destructive のボタンが赤い背景でレンダリングされます。

AddAction メソッドは、指定されたアクションを UIAlertViewController に追加し、最後に PresentViewController (alertController, true, null) メソッドによって指定されたアラートがユーザーに表示されます。

テキスト フィールドの追加

アラートにアクション (ボタン) を追加するだけでなく、テキスト フィールドをアラートに追加して、ユーザー ID やパスワードなどの情報を入力できます。

アラート内のテキスト フィールド

ユーザーがテキスト フィールドを選択すると、標準の tvOS キーボードが表示され、フィールドの値を入力できるようになります。

テキストの入力

次のコードは、値を入力するための単一のテキスト フィールドを含む OK/キャンセル アラートを表示します。

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 でユーザーにアラート メッセージを表示する方法について説明しました。 最初に、簡単なアラートを表示し、ボタンを追加する方法を示しました。 次に、アラートにテキスト フィールドを追加する方法を示しました。 最後に、ヘルパー クラスを使用して、アラートを表示するために必要な繰り返しコードの量を減らす方法を示しました。