您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 MonoTouch.Dialog 快速搭出 iOS 表單界面

編輯:iOS 開發綜合

MonoTouch.Dialog(簡稱 MT.D)是 Xamarin.iOS 的 RAD 工具包,作者正是 Xamarin 的 CTO Miguel de Icaza。它的核心概念很簡單:用程式碼描述資料結構,自動生成表格 UI,不必手動排無數個 UITableViewCell。

兩套 API,兩種取向

  • Low-level Elements API:以樹狀結構(類似 DOM)描述 UI 與各部件,彈性最大,並支援用 JSON 動態產生界面。
  • High-Level Reflection API:又稱綁定 API,用 Attribute 標記在實體類別的屬性上,自動產生 UI 並完成雙向綁定。缺點是無法做細粒度控制。

四個核心組成

  • DialogViewController(DVC):繼承自 UITableViewController,所有 MT.D 元素都要靠它呈現。
  • RootElement:最上層容器,本身不顯示,只承載 Section。
  • Section:分組,對應 UITableView 的 section,可設 Header 與 Footer(文字或自訂 view)。
  • Element:最基本的控件,對應一個 cell。

DVC 的初始化

var dvc = new DialogViewController(UITableViewStyle.Plain, root);

參數依序是列表樣式、根元素,以及 pushing(是否顯示返回按鈕,搭配 UINavigationController 時使用)。實務上多半會繼承 DVC 來定制:

class LwmeViewController: DialogViewController {
    public LwmeViewController(): base(UITableViewStyle.Plain, null) {
        this.Root = new RootElement("囧月") {
            // 在這裡建立 Section 與 Element
        };
    }
}

若要放入導航控制器:

nav = new UINavigationController(new DialogViewController(root));
window.RootViewController = nav;

RootElement 與巢狀結構

RootElement 也可以當成 Section 的子元素;被點擊時會推入一個新視圖,這是做「多層表單」的關鍵:

var root = new RootElement("Meals") {
    new Section("Dinner") {
        new RootElement("Dessert", new RadioGroup("dessert", 2)) {
            new Section() {
                new RadioElement("Ice Cream", "dessert"),
                new RadioElement("Milkshake", "dessert"),
                new RadioElement("Chocolate Cake", "dessert")
            }
        }
    }
};

搭配 LINQ 與 C# 3.0 的集合初始化語法,可以很輕易地從資料動態生成整棵樹:

var root = new RootElement("囧月-lwme.cnblogs.com") {
    new string[] {"隨筆", "評論", "RSS"}.Select(
        x => new Section(x) {
            "內容1,內容2,內容3".Split(',').Select(
                s => new StringElement(s, delegate {
                    Console.WriteLine("內容被點擊");
                })
            )
        }
    )
};

Section 的 Header/Footer 也能放自訂 view:

var section = new Section(new UIImageView(Image.FromBundle("header.png")));

內建元素速覽

  • StringElement:左 Caption、右 Value 的普通文字;StyledStringElement 可設字型、顏色、背景與行數。
  • MultilineElement / StyledMultilineElement:多行版本。
  • EntryElement:文字輸入,可設 Placeholder、isPassword,並用 KeyboardType 限制輸入(Numeric、Phone、Url、Email)。
  • BooleanElement / CheckboxElement / RadioElement:對應 UISwitch、核取方塊與單選;RadioElement 必須放在有 RadioGroup 的 RootElement 底下。
  • FloatElement:UISlider。
  • DateElement / TimeElement / DateTimeElement:各類日期時間選擇器。
  • HtmlElement:點擊後開啟 UIWebView 載入網址。
  • ImageElement / ImageStringElement / BadgeElement:圖片與圖示型元素。
  • ActivityElement / LoadMoreElement:載入動畫與「載入更多」。
  • MessageElement:類似收件匣的樣式,可設 Body、Sender、Subject、Date 等。
  • JsonElement:從 JSON 直接產生界面。
  • UIViewElement / OwnerDrawnElement:放入任意 UIView,或繼承後完全自繪。

動作與取值

大部分元素都有一個 NSAction 型別的 Tapped 事件:

new StringElement("點我", delegate { Console.WriteLine("元素被點擊"); })

取值時直接讀元素的 Value 屬性:

var element = new EntryElement("評論", "輸入評論內容", null);
// ...
new StringElement("獲取", delegate { Console.WriteLine(element.Value); })

要注意的一點:有些屬性改了不會反映到畫面上。EntryElement.Value 可以直接設;但 StringElement.Caption、StringElement.Value 這類不行,必須呼叫 Reload 才會更新:

se.Caption = "新標題";
se.Value = DateTime.Now.ToString();
root.Reload(se, UITableViewRowAnimation.None);

反射 API:用 Attribute 描述表單

class Blogger {
    [Section("登錄博客"), Entry("輸入用戶名"), Caption("用戶名")]
    public string Username;

    [Password("輸入密碼"), Caption("密碼")]
    public string Password;

    [Checkbox, Caption("下次自動登錄")]
    public bool Remember;

    [Section("開始登錄", "請確認你輸入的信息"), Caption("登錄"), OnTap("Login")]
    public string DoLogin;
}

public class LwmeViewController: DialogViewController {
    BindingContext context;
    Blogger blog;

    public LwmeViewController(): base(UITableViewStyle.Grouped, null) {
        blog = new Blogger { Username = "囧月" };
        context = new BindingContext(this, blog, null);
        this.Root = context.Root;
    }

    public void Login() {
        context.Fetch();   // 把畫面上的輸入同步回物件
        if (string.IsNullOrWhiteSpace(blog.Username) ||
            string.IsNullOrWhiteSpace(blog.Password)) {
            new UIAlertViewController("出錯提示", "用戶名和密碼必須填寫", null, "確定", null).Show();
        }
    }
}

型別必須對應,否則元素不會被產生:EntryElement 只能配 string;FloatElement 只能配 float(double、decimal 無效);BooleanElement 只能配 bool;RadioElement 只能配 enum 或 int(搭配實作 IEnumerable 的資料源)。

可用的 Attribute 有 Entry、Password、Checkbox、Date、Time、DateTime、Html、Multiline、RadioSelection、Caption、Alignment、OnTap、Range、Skip。而 string / bool / float 這三種型別沒有對應 Attribute,會各自被產生為 StringElement、BooleanElement、FloatElement。

非同步時的注意事項:登入這類操作通常要用 WebClient 的 UploadStringAsync 避免阻塞 UI,但回呼時已不在 UI 執行緒上,必須用 InvokeOnMainThread 或 BeginInvokeOnMainThread 切回來才能操作界面。

JSON 元素

{
  "title": "囧月",
  "sections": [
    { "elements": [
        { "id": "lwme-username", "type": "entry",
          "caption": "用戶名", "placeholder": "輸入用戶名" },
        { "id": "lwme-date", "type": "date", "caption": "日期", "value": "00:00" }
    ] }
  ]
}
var root = JsonElement.FromFile("lwme.json");                    // 本地
var root = new JsonElement("load from json", "lwme.cnblogs.com/lwme.json");  // 遠端
var dvc = new DialogViewController(root);

// 以 id 取出元素
var username = root["lwme-username"] as EntryElement;

這種做法能讓界面完全由後端資料驅動,同時大幅縮小客戶端包體積。

其他實用特性

下拉刷新

dvc.RefreshRequested += (s, e) => {
    // 處理資料...
    dvc.ReloadComplete();
};

也可用 TriggerRefresh() 主動觸發,或覆寫 MakeRefreshTableHeaderView(RectangleF) 自訂刷新頭。

搜尋

只要設定 EnableSearch = true 即可啟用;需要更細的控制時可用 StartSearch()、FinishSearch()、PerformFilter() 等方法與 SearchTextChanged 事件。

背景載入圖片

new BadgeElement(
    ImageLoader.DefaultRequestImage(new Uri("https://lwme.cnblogs.com/xx.png"), this),
    "囧月")

下載的圖會被記憶體快取(預設 50 張),可用 ImageLoader.Purge() 清除。

自訂元素

繼承 Element 或 OwnerDrawnElement,視需求覆寫:GetCell(必須)、GetHeight、Dispose、Summary、Selected、Matches(要支援搜尋時)以及 CellKey。

關於資料驗證

MT.D 沒有內建驗證機制,需要自己在 Tapped 事件裡判斷:

new StringElement("獲取", delegate {
    if (string.IsNullOrEmpty(ee.Value)) {
        new UIAlertViewController("出錯提示", "內容必須填寫", null, "確定", null).Show();
    }
})

總結

MT.D 的價值在於「用資料描述界面」:反射 API 適合快速把物件變成表單,元素 API 適合需要精細控制的頁面,JSON 元素則適合由後端驅動的動態界面。三者可以混用,甚至只在局部頁面引入,是 Xamarin.iOS 專案裡相當值得一試的工具。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved