MonoTouch.Dialog(簡稱 MT.D)是 Xamarin.iOS 的 RAD 工具包,作者正是 Xamarin 的 CTO Miguel de Icaza。它的核心概念很簡單:用程式碼描述資料結構,自動生成表格 UI,不必手動排無數個 UITableViewCell。
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 也可以當成 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")));
大部分元素都有一個 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);
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 切回來才能操作界面。
{
"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 專案裡相當值得一試的工具。