SIN@SAPPOROWORKSの覚書

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

Xamarin.iOS モーダルビュー

【 Xamarin 記事一覧 】

1 オープン・クローズ

f:id:furuya02:20140702051215p:plain:w150:leftf:id:furuya02:20140702051214p:plain:w150:left

モーダルビューを表示するには、PresentViewControllerを使用します。

public override void ViewDidLoad() {
    base.ViewDidLoad();

    //「Open」ボタンを押した時のイベント処理
    button1.TouchUpInside += (sender, args) =>{
        //ビューの生成
        var view = new MyModalView();
        //モーダルビューの表示
        PresentViewController(view, true, null);
    };
}

モーダルビューを閉じるには、DismissViewControllerを使用します。

//モーダルビューの定義
class MyModalView :UIViewController{

    public override void ViewDidLoad(){
        base.ViewDidLoad();
        
        //分かりやすいようにビューをオレンジ色にする
        View.BackgroundColor = UIColor.Orange;

        //「Close」ボタンの生成
        var button = new UIButton(UIButtonType.RoundedRect) {
            Bounds = new RectangleF(0,0,100,30),
            Center = new PointF(View.Bounds.Width/2, View.Bounds.Height/2), //画面中央
        };
        button.SetTitle("Close",UIControlState.Normal);
        //ボタンを押した時のイベント処理
        button.TouchUpInside += (s, e) => {
            //モーダルビューを閉じる
            DismissViewController(true, null);
        };
        Add(button);//ビューへの追加
    }
}

2 ストーリボードによる方法

f:id:furuya02:20140702051343p:plain:w300:left
Controlキーを押しながら、「Open」ボタンから、遷移先のビューへドラッグし、ドロップ時に表示されるポップアップで「Modal」を選択します。


f:id:furuya02:20140702051409p:plain:w300:left
ビューの間にセグエが表示され、プロパティのWidgetでStyleがModalになっていることを確認できます。


f:id:furuya02:20140702051428p:plain:w300:left
「Close」ボタンの処理を記述するには、新しいビューのクラスを作成する必要があります。
ストーリボードで、ビューコントローラを選択し、プロパティのWidgetでClass名を入力します。


f:id:furuya02:20140702051445p:plain:w300:left
ソリューションエクスプローラに戻ると、新しいクラスが追加されていることを確認できます。
後は、このクラスにボタンを押した時のイベント処理を書き込むだけです。

partial class MyModalView : UIViewController{
    public override void ViewDidLoad(){
        base.ViewDidLoad();
        //「Close」ボタンを押した時のイベント
        buttonClose.TouchUpInside += (s, e) => {
            //モーダルビューを閉じる
            DismissViewController(true, null);
        };
    }
}

3 表示オプション

f:id:furuya02:20140702051517p:plain:w300:left
ビュー遷移時のアニメーションは、表示されるビューのプロパティ(ModalTransitionStyle)で指定できます。


指定可能なスタイルは、下記の4種類です。
UIModalTransitionStyle.CoverVertical (上下にスライド)
UIModalTransitionStyle.CrossDissolve (クロスフィード)
UIModalTransitionStyle.FlipHorizontal (左右に3次元回転)
UIModalTransitionStyle.PartialCurl (めくりあげ)

4 モーダル表示直後の処理

f:id:furuya02:20140702051532p:plain:w150:left
PresentViewController()の第3パラメータ及びDismissViewController()の第2パラメータで、画面遷移直後の処理を記述できます。
次のコードは、モーダル表示直後にアラートダイアログを表示させたものです。

//モーダルビューの表示
PresentViewController(view, true, () =>{
    (new UIAlertView("タイトル", "メッセージ", null, null, "OK")).Show();
});

【 Xamarin 記事一覧 】