developer's diary

最近はc#のエントリが多いです

UIButtonをクリックしてUIAlertViewを表示。イベントにはラムダ式を利用でコードスッキリ。

今日も朝はiOS(C#)コーディング。

UIControllerにUIButtonを追加してボタンを押すと、UIAlertViewを表示する簡単なサンプル。 イベントの登録にラムダ式を使えるので、コードはとてもスッキリ。

using System;
using MonoTouch.UIKit;
using System.Drawing;
namespace UIKitExample
{
    public class UIViewExample : UIViewController
    {

        public UIViewExample ()
        {
            //背景色設定
            this.View.BackgroundColor = new UIColor (1.0f, 1.0f, 1.0f, 1.0f);

            //UIButton生成
            UIButton btn = new UIButton(UIButtonType.RoundedRect);

            //ボタンのタイトル設定
            btn.SetTitle ("click", UIControlState.Normal);

            //ボタンの表示位置設定
            btn.Frame = new RectangleF (10.0f, 10.0f, 100.0f, 30.0f);

            //ボタンタッチアップ時のイベント
            btn.TouchUpInside += (sender, e) => {
                //UIAlertViewを生成して表示
                new UIAlertView("alert title","alert body",null,"alert button title", null).Show(); 
            };

            //ボタンをUIViewControllerのViewに追加
            this.View.AddSubview(btn);

        }
    }
}
f:id:mitsugi-bb:20130302084747p:plain
f:id:mitsugi-bb:20130302084751p:plain

Generic.Dictionaryも使ってみた。

using System;
using MonoTouch.UIKit;
using System.Drawing;
using System.Collections.Generic;

namespace UIKitExample
{
    public class UIViewExample : UIViewController
    {

        public UIViewExample ()
        {
            this.View.BackgroundColor = new UIColor (1.0f, 1.0f, 1.0f, 1.0f);

            Dictionary<String, String> dic = new Dictionary<String,String> ();
            dic.Add ("buttonA", "buttonA Click!");
            dic.Add ("buttonB", "buttonB Click!");
            dic.Add ("buttonC", "buttonC Click!");
            dic.Add ("buttonD", "buttonD Click!");
            dic.Add ("buttonE", "buttonE Click!");
            dic.Add ("buttonF", "buttonF Click!");

            float y = 10.0f;
            foreach (KeyValuePair<String,String> kvp in dic) {
                String buttonName = kvp.Key;
                String buttonClickActionMessage = kvp.Value;

                UIButton btn = new UIButton(UIButtonType.RoundedRect);
                btn.SetTitle (buttonName, UIControlState.Normal);
                btn.Frame = new RectangleF (10.0f, y, 100.0f, 30.0f);
                btn.TouchUpInside += (sender, e) => {
                    new UIAlertView("alert title",buttonClickActionMessage,null,"alert button title", null).Show(); 
                };              
                this.View.AddSubview(btn);
                y += 40.0f;

            }
        }
    }
}

foreachでボタンを配置。

f:id:mitsugi-bb:20130302114046p:plain