LoginSignup
6
6

More than 5 years have passed since last update.

Xamarinで遊ぶ(2) DialogViewController

Last updated at Posted at 2014-08-26

←前 次→

DialogViewControllerを作ります。
新しいファイルから「DialogViewController」を選択して作ると、サンプルコード込みでファイルが生成されます。
Banners_and_Alerts_と_新しいファイル.png

HomeViewController.cs
using System;
using System.Collections.Generic;
using System.Linq;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.Dialog;

namespace MyTasky.Screens
{
    public partial class HomeViewController : DialogViewController
    {
        public HomeViewController () : base (UITableViewStyle.Grouped, null)
        {
            Root = new RootElement ("HomeScreen"){
                new Section ("First Section") {
                    new StringElement ("Hello", () => {
                        new UIAlertView ("Hola", "Thanks for tapping!", null, "Continue").Show (); 
                    }),
                    new EntryElement ("Name", "Enter your name", String.Empty)
                },
                new Section ("Second Section") {
                },
            };
        }
    }
}

これだけで、TableViewにいくつかCellの乗った状態で画面が作られます。

スクリーンショット_2014_08_26_22_43.png

DialogViewController

DialogViewControllerは、UITableViewControllerを継承しているのですが、パッケージが独自のMonoTouch.Dialogに分類されており、組み合わせて使うクラスが多数用意されているので、「使いにくいUITableViewControllerをC#から使いやすくした便利クラス」なのだと思います。

コレクション初期化子という書き方

ソースを見ると、

Root = new RootElement(){
  new Section(){..},
  new Section(){..},
}

という、「コンストラクタ」+「配列」が組合わさった、見慣れない書き方がされてます。これはコレクション初期化子という書き方のようです。これは、IEnumerableインタフェースを実装するクラスのコンストラクタに{} で繋げると、その中のオブジェクトを引数にAdd()メソッドを呼び出していくようです。

なので、生成されたサンプルコードは、↓と同じ意味となりますが、断然コレクション初期化子の方が読みやすいですよね。

            Root = new RootElement ("HomeScreen");
            var section1 = new Section ("First Section");
            section1.Add (new StringElement ("Hello", () => {
                new UIAlertView ("Hola", "Thanks for tapping!", null, "Continue").Show (); 
            }));
            section1.Add (new EntryElement ("Name", "Enter your name", String.Empty));
            Root.Add (section1);
            Root.Add (new Section ("Second Section"));

RootElementのAddメソッドをオーバーライドしようとしたら、出来なかった

コレクション初期化子の挙動を確認するため、RootElementを継承したMyRootElementを作って、Addメソッドをオーバーライドしようと思ったら、エラーが出て出来ませんでした。
この辺の継承ルールはちょっとお固めなのですね。
XamarinStudio_と_Banners_and_Alerts_と_MyTasky_-_Screens_HomeViewController_cs_-_Xamarin_Studio.png

沢山あるElementの仲間

XamarinのDocumentのIntroduction to MonoTouch.Dialogを見てると、UITableViewCellの代わりに使えそうなStringElement,BooleanElementから、HTMLElementやらJSONElementなんて不思議なものまで見つける事が出来ます。ここはここで別途要チェックです。

MT.D = MonoTouch.Dialog

色々見てると、MT.Dと省略している所が多いですね。それだけこれはよく使う所なのでしょう。

ここまでのソース

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6