SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

xamarin.iOS アラートダイアログ・アクションシート

【 Xamarin 記事一覧 】

1 アラートダイアログ

f:id:furuya02:20140607143042p:plain:w150:left
UIAlertView()でアラートダイログを表示できます。

var alert = new UIAlertView("タイトル", "メッセージ", null, "Cancel","OK");
alert.Show();

f:id:furuya02:20140607143043p:plain:w300:left
ボタンクリック時のイベントは、Clickedで取得できます。
UIAlertView()の第3パラメータで、クリックイベントを処理するクラス(UIAlertViewDelegate)を指定することも可能ですが、
イベント+ラムダで書いた方が、色々な意味で個人的に好きです。

var alert = new UIAlertView("タイトル", "メッセージ", null, "OK", new [] { "Cancel" });
alert.Clicked += (sender, args) => Console.WriteLine("{0} Clicked", args.ButtonIndex);
alert.Show();

f:id:furuya02:20140607143149p:plain:w150:left
タイトル、メッセージ、ボタンは、プロパティやメソッドでも指定可能です。
ボタンを2つを超えると縦に並びます。

var alert = new UIAlertView() {
    Title = "タイトル",
    Message = "メッセージ"
};
alert.AddButton("1");
alert.AddButton("2");
alert.AddButton("3");
alert.AddButton("4");
alert.AddButton("5");
alert.AddButton("6");
alert.Clicked += (sender, args) => Console.WriteLine("{0} Clicked", args.ButtonIndex);
alert.Show();

AlertViewStyleにスタイルを指定するだけで、下記の形のダイアログを作成できます。

(1)UIAlertViewStyle.LoginAndPasswrdInput
(2)UIAlertViewStyle.PlainTextInput
(3)UIAlertViewStyle.SecureTextInput

f:id:furuya02:20140607151326p:plain:w150:leftf:id:furuya02:20140607151324p:plain:w150:leftf:id:furuya02:20140607151325p:plain:w150:left

なお、テキストフィールドへの入力内容は、GetTextField(index)で取得できます。

var alert = new UIAlertView("タイトル", "メッセージ", null, "OK", null){
    AlertViewStyle = UIAlertViewStyle.LoginAndPasswordInput//スタイルの指定
};
//Loginとpasswordに入力されたテキストをGetTextField(n).Textで取得する
alert.Clicked += (sender, args) => Console.WriteLine(String.Format("login:{0} pass:{1}", alert.GetTextField(0).Text, alert.GetTextField(1).Text));
alert.Show();


2 アクションシート

f:id:furuya02:20140607143150p:plain:w150:left
複数の選択肢の中から1つ選択をさせたい時、UIActionSheet()が使用できます。
Clickedイベント時に受け取るButtonIndexは、ボタンの種類に関係なく、上から数えたインデックスとなります。
(図では、「メニュー1」が0、「メニュー2」が1、「キャンセル」が3です)

var actionSheet = new UIActionSheet ("タイトル", null, "キャンセル","メニュー1", new[]{"メニュー2","メニュー3"});
actionSheet.Clicked += (sender, args) => Console.WriteLine("{0} Clicked", args.ButtonIndex);
actionSheet.ShowInView(View);

f:id:furuya02:20140607143151p:plain:w150:left
UIActionSheet()もプロパティやメソッドで記述できます。
DestructiveButtonIndexは、赤色表示するボタン位置、そして、CancelButtonIndexは、キャンセルボタンの位置指定です。(最後のインデックス以外を指定すると、ちょっと表示が違うようです)

var actionSheet = new UIActionSheet(){
    Title="タイトル"
};
actionSheet.AddButton("1");
actionSheet.AddButton("2");
actionSheet.AddButton("3");
actionSheet.AddButton("4");

actionSheet.DestructiveButtonIndex = 1; // 赤色で表示される
actionSheet.CancelButtonIndex = 3;  // 最後のインデックスを指定した場合スペースが挿入される
actionSheet.Clicked += (sender, args) => Console.WriteLine("{0} Clicked", args.ButtonIndex);
actionSheet.ShowInView(View);


【 Xamarin 記事一覧 】