mono android单选按钮,适用于 Xamarin 的 Monotouch.dialog 简介

适用于 Xamarin 的 Monotouch.dialog 简介Introduction to MonoTouch.Dialog for Xamarin.iOS

11/25/2015

本文内容

Monotouch.dialog,称为 MT。D 对于 short,是一种快速 UI 开发工具包,使开发人员能够使用信息而不是创建视图控制器、表等的麻烦来构建应用程序屏幕和导航。因此,它可显著简化 UI 开发和代码缩减。MonoTouch.Dialog, referred to as MT.D for short, is a rapid UI development toolkit that allows developers to build out application screens and navigation using information, rather than the tedium of creating view controllers, tables, etc. As such, it provides a significant simplification of UI development and code reduction. 例如,请看下面的屏幕截图:For example, consider the following screenshot:

bc47b00315b53fc99f38656a204befcd.pngbc47b00315b53fc99f38656a204befcd.png

以下代码用于定义此整个屏幕:The following code was used to define this entire screen:

public enum Category

{

Travel,

Lodging,

Books

}

public class Expense

{

[Section("Expense Entry")]

[Entry("Enter expense name")]

public string Name;

[Section("Expense Details")]

[Caption("Description")]

[Entry]

public string Details;

[Checkbox]

public bool IsApproved = true;

[Caption("Category")]

public Category ExpenseCategory;

}

在 iOS 中使用表时,通常会有大量重复使用的代码。When working with tables in iOS, there’s often a ton of repetitious code.

例如,每次需要表时,都需要使用数据源来填充该表。For example, every time a table is needed, a data source is needed to populate that table. 在具有两个通过导航控制器连接的基于表的屏幕的应用程序中,每个屏幕共享大量相同的代码。In an application that has two table-based screens that are connected via a navigation controller, each screen shares a lot of the same code.

隶书.D 通过将所有这些代码封装到用于创建表的泛型 API 中来简化此过程。MT.D simplifies that by encapsulating all of that code into a generic API for table creation. 然后,它在该 API 的顶层提供了一个抽象,它允许使用声明性对象绑定语法,使其变得更加简单。It then provides an abstraction on top of that API that allows for a declarative object binding syntax that makes it even easier. 在这种情况下,MT 提供两个 Api。2-dAs such, there are two APIs available in MT.D:

低级别元素 api – 元素 api 基于创建元素的层次结构树,这些元素表示屏幕及其组件。Low-level Elements API – The Elements API is based on creating a hierarchal tree of elements that represent screens and their components. 元素 API 为开发人员提供了最大的灵活性和控制。The Elements API gives developers the most flexibility and control in creating UIs. 此外,元素 API 通过 JSON 提供对声明性定义的高级支持,这允许实现极其快速的声明,以及从服务器动态地生成 UI。Additionally, the Elements API has advanced support for declarative definition via JSON, which allows for both incredibly fast declaration, as well as dynamic UI generation from a server.

高级别反射 api (也称为 绑定 api ),其中的类用 UI 提示和 MT 进行批注。D 基于对象自动创建屏幕,并在显示的内容之间提供绑定 (,还可以选择在屏幕上编辑) 和基础对象支持。High-Level Reflection API – Also known as the Binding API , in which classes are annotated with UI hints and then MT.D automatically creates screens based on the objects and provides a binding between what is displayed (and optionally edited) on screen, and the underlying object backing. 上面的示例演示了反射 API 的用法。The example above illustrated the use of the Reflection API. 此 API 不提供元素 API 执行的精细控制,但通过基于类属性自动生成元素层次结构,进一步降低了复杂性。This API doesn’t provide the fine-grained control that the elements API does, but it reduces complexity even further by automatically building out the element hierarchy based on class attributes.

隶书.D 附带了大量内置 UI 元素,用于创建屏幕,但它也能识别自定义元素和高级屏幕布局的需求。MT.D comes packed with a large set of built in UI elements for screen creation, but it also recognizes the need for customized elements and advanced screen layouts. 因此,可扩展性是融入 API 的一流功能。As such, extensibility is a first-class featured baked into the API. 开发人员可以扩展现有元素,或创建新元素,然后无缝集成。Developers can extend the existing elements or create new ones and then integrate seamlessly.

此外,MT。D 中内置了许多常见的 iOS UX 功能,如 "请求刷新" 支持、异步映像加载和搜索支持。Additionally, MT.D has a number of common iOS UX features built in such as “pull-to-refresh” support, asynchronous image loading, and search support.

本文将全面介绍如何使用 MT。D. 包括:This article will take a comprehensive look at working with MT.D, including:

MT。D 组件 –这将重点介绍构成 MT 的类。D:使快速启动速度更快。MT.D Components – This will focus on understanding the classes that make up MT.D to enable getting up to speed quickly.

元素参考 – MT. d. 内置元素的完整列表。Elements Reference – A comprehensive list of the built-in elements of MT.D.

高级用法 –这涉及到一些高级功能,例如:请求刷新、搜索、背景图像加载、使用 LINQ 生成元素层次结构,以及创建自定义元素、单元和控制器以与 MT 一起使用。Advanced Usage – This covers advanced features such as pull-to-refresh, search, background image loading, using LINQ to build out element hierarchies, and creating custom elements, cells, and controllers for use with MT.D.

设置 MT。2-dSetting up MT.D

隶书.D 与 Xamarin 一起分发。MT.D is distributed with Xamarin.iOS. 若要使用此方法,请右键单击 Visual Studio 2017 或 Visual Studio for Mac 中的 Xamarin iOS 项目的 " 引用 " 节点,然后添加对 monotouch.dialog 程序集的引用。To use it, right-click on the References node of a Xamarin.iOS project in Visual Studio 2017 or Visual Studio for Mac and add a reference to the MonoTouch.Dialog-1 assembly. 然后, using MonoTouch.Dialog 根据需要在源代码中添加语句。Then, add using MonoTouch.Dialog statements in your source code as necessary.

了解 MT 的各个部分。2-dUnderstanding the Pieces of MT.D

即使使用反射 API,MT 也是如此。D 在其下创建一个元素层次结构,就像是直接通过元素 API 创建的一样。Even when using the Reflection API, MT.D creates an Element hierarchy under the hood, just as if it were created via the Elements API directly. 此外,在上一节中提到的 JSON 支持也会创建元素。Also, the JSON support mentioned in the previous section creates Elements as well. 出于此原因,重要的一点是要对 MT 的构成部分有一个基本的了解。For this reason, it’s important to have a basic understanding of the constituent pieces of MT.D.

隶书.D 使用以下四个部分生成屏幕:MT.D builds screens using the following four parts:

DialogViewControllerDialogViewController

RootElementRootElement

节Section

元素Element

DialogViewControllerDialogViewController

DialogViewController(简称DVC )继承自, UITableViewController 因此表示包含表的屏幕。A DialogViewController, or DVC for short, inherits from UITableViewController and therefore represents a screen with a table. DVCs 可以像常规 UITableViewController 一样推送到导航控制器上。DVCs can be pushed onto a navigation controller just like a regular UITableViewController.

RootElementRootElement

RootElement是进入 DVC 的项的顶级容器。A RootElement is the top-level container for the items that go into a DVC. 它包含一些部分,然后可以包含元素。It contains Sections, which can then contain Elements. 不呈现 RootElements;它们只是容器来表示实际呈现的内容。RootElements are not rendered; instead they’re simply containers for what actually gets rendered. 将 RootElement 分配给 DVC,然后 DVC 呈现其子级。A RootElement is assigned to a DVC, and then the DVC renders its children.

部分Section

节是表中的一组单元。A section is a group of cells in a table. 与普通的表部分一样,它可以有可能是文本的页眉和页脚,甚至是自定义视图,如以下屏幕截图所示:As with a normal table section, it can optionally have a header and footer that can either be text, or even custom views, as in the following screenshot:

91983fdd25b73dd019b72aea7a4b11e8.png91983fdd25b73dd019b72aea7a4b11e8.png

元素Element

元素表示表中的实际单元。An Element represents an actual cell in the table. 隶书.D 打包了各种元素,这些元素表示不同的数据类型或不同的输入。MT.D comes packed with a wide variety of Elements that represent different data types or different inputs. 例如,以下屏幕截图演示了一些可用元素:For example, the following screenshots illustrate a few of the available elements:

0775362689652c7edbc87ab4cd147d21.png0775362689652c7edbc87ab4cd147d21.png

有关节和 RootElements 的详细信息More on Sections and RootElements

现在,让我们更详细地讨论 RootElements 和章节。Let’s now discuss RootElements and Sections in greater detail.

RootElementsRootElements

需要至少一个 RootElement 才能启动 Monotouch.dialog 进程。At least one RootElement is required to start the MonoTouch.Dialog process.

如果使用节/元素值初始化 RootElement,则此值用于查找将提供配置摘要的子元素,该配置将呈现在显示内容的右侧。If a RootElement is initialized with a section/element value then this value is used to locate a child Element that will provide a summary of the configuration, which is rendered on the right side of the display. 例如,下面的屏幕截图在左侧显示一个表,其中包含右侧的详细信息屏幕标题 "甜品" 以及所选沙漠的值。For example, the screenshot below shows a table on the left with a cell containing the title of the detail screen on the right, “Dessert”, along with the value of the selected desert.

feeb9fa97915c702d18cb7c9703336ee.png。下面的a8343398ab1cd94be5aa828a6d87f13c.pngfeeb9fa97915c702d18cb7c9703336ee.pnga8343398ab1cd94be5aa828a6d87f13c.png

此外,还可以在部分中使用根元素来触发加载新的嵌套配置页,如上所示。Root elements can also be used inside Sections to trigger loading a new nested configuration page, as shown above. 在此模式下使用时,将在部分中呈现时使用提供的标题,并将其用作子页的标题。When used in this mode the caption provided is used while rendered inside a section and is also used as the Title for the subpage. 例如:For example:

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")

}

}

}

};

在上面的示例中,当用户点击 "甜品" 时,Monotouch.dialog 会创建一个新页面,并导航到根为 "甜品" 的单选按钮,并具有具有三个值的单选组。In the above example, when the user taps on "Dessert", MonoTouch.Dialog will create a new page and navigate to it with the root being "Dessert" and having a radio group with three values.

在此特定示例中,单选组将在 "甜品" 部分中选择 "巧克力蛋糕",因为我们将值 "2" 传递到 RadioGroup。In this particular sample, the radio group will select "Chocolate Cake" in the "Dessert" section because we passed the value "2" to the RadioGroup. 这意味着选取列表中的第三项 (零索引) 。This means pick the 3rd item on the list (zero-index).

调用 Add 方法或使用 c # 4 初始值设定项语法添加部分。Calling the Add method or using the C# 4 initializer syntax adds sections.

提供插入方法以插入带有动画的部分。The Insert methods are provided to insert sections with an animation.

如果使用 (而不是) RadioGroup 的组实例创建 RootElement,则在部分中显示的 RootElement 的汇总值将是与该组具有相同键的所有 BooleanElements 和 CheckboxElements 的累计计数。If you create the RootElement with a Group instance (instead of a RadioGroup) the summary value of the RootElement when displayed in a Section will be the cumulative count of all the BooleanElements and CheckboxElements that have the same key as the Group.Key value.

部分Sections

节用于对屏幕中的元素进行分组,它们是 RootElement 的唯一直接子项。Sections are used to group elements in the screen and they are the only valid direct children of the RootElement. 节可以包含任何标准元素,包括 new RootElements。Sections can contain any of the standard elements, including new RootElements.

部分中嵌入的 RootElements 用于导航到新的更深级别。RootElements embedded in a section are used to navigate to a new deeper level.

节可以包含字符串形式的页眉和页脚,也可以是 UIViews。Sections can have headers and footers either as strings, or as UIViews.

通常只使用字符串,但若要创建自定义 Ui,可以使用任何 UIView 作为页眉或页脚。Typically you will just use the strings, but to create custom UIs you can use any UIView as the header or the footer. 您可以使用字符串创建它们,如下所示:You can either use a string to create them like this:

var section = new Section ("Header", "Footer");

若要使用视图,只需将视图传递到构造函数:To use views, just pass the views to the constructor:

var header = new UIImageView (Image.FromFile ("sample.png"));

var section = new Section (header);

收到通知Getting Notified

处理 NSActionHandling NSAction

隶书.D 将曲面 NSAction 作为处理回调的委托。MT.D surfaces an NSAction as a delegate for handling callbacks.

例如,假设您想要为由 MT 创建的表格单元处理触控事件。For example, say you want to handle a touch event for a table cell created by MT.D. 使用 MT 创建元素时。D. 只需提供一个回调函数,如下所示:When creating an element with MT.D, simply supply a callback function, as shown below:

new Section () {

new StringElement ("Demo Callback", delegate { Console.WriteLine ("Handled"); })

}

正在检索元素值Retrieving Element Value

与属性结合后 Element.Value ,回调可以检索其他元素中设置的值。Combined with the Element.Value property, the callback can retrieve the value set in other elements. 例如,考虑以下代码:For example, consider the following code:

var element = new EntryElement (task.Name, "Enter task description", task.Description);

var taskElement = new RootElement (task.Name) {

new Section () { element },

new Section () { new DateElement ("Due Date", task.DueDate) },

new Section ("Demo Retrieving Element Value") {

new StringElement ("Output Task Description", delegate { Console.WriteLine (element.Value); })

}

};

此代码将创建一个 UI,如下所示。This code creates a UI as shown below. 有关此示例的完整演练,请参阅 元素 API 演练 教程。For a complete walkthrough of this example, see the Elements API Walkthrough tutorial.

7372dccb2c24b022885e0ae72d5a17dd.png7372dccb2c24b022885e0ae72d5a17dd.png

当用户按下下表单元时,将执行匿名函数中的代码,并将此实例中的值写入 element Visual Studio for Mac 中的 应用程序输出 板。When the user presses the bottom table cell, the code in the anonymous function executes, writing the value from the element instance to the Application Output pad in Visual Studio for Mac.

内置元素Built-In Elements

隶书.D 附带了多个称为元素的内置表单元项。MT.D comes with a number of built-in table cell items known as Elements.

这些元素用于显示表单元格中各种不同的类型,如字符串、浮动、日期甚至图像,只需进行几次命名即可。These elements are used to display a variety of different types in table cells such as strings, floats, dates and even images, to name just a few. 每个元素都负责正确显示数据类型。Each element takes care of displaying the data type appropriately. 例如,布尔值元素将显示开关来切换其值。For example, a boolean element will display a switch to toggle its value. 同样,float 元素会显示滑块来更改 float 值。Likewise, a float element will display a slider to change the float value.

还有更复杂的元素来支持更丰富的数据类型,例如图像和 html。There are even more complex elements to support richer data types such as images and html. 例如,一个 html 元素,它将打开一个 UIWebView 以在选中时加载网页,并在表单元格中显示标题。For example, an html element, which will open a UIWebView to load a web page when selected, displays a caption in the table cell.

使用元素值Working with Element Values

用于捕获用户输入的元素公开公共 Value 属性,该属性随时都保存元素的当前值。Elements that are used to capture user input expose a public Value property that holds the current value of the element at any time. 当用户使用该应用程序时,它会自动更新。It is automatically updated as the user uses the application.

这是 Monotouch.dialog 中所有元素的行为,但用户创建的元素不需要此行为。This is the behavior for all of the Elements that are part of MonoTouch.Dialog, but it is not required for user-created elements.

String 元素String Element

在 StringElement 表单元的左侧显示一个标题,并显示单元格右侧的字符串值。A StringElement shows a caption on the left side of a table cell and the string value on the right side of the cell.

06b5a705ced5a7d485e318692ffcc279.png06b5a705ced5a7d485e318692ffcc279.png

若要使用 StringElement 作为按钮,请提供委托。To use a StringElement as a button, provide a delegate.

new StringElement ("Click me", () => {

new UIAlertView("Tapped", "String Element Tapped", null, "ok", null).Show();

});

b18374e39fdd1766055e06a7a7f38e93.pngb18374e39fdd1766055e06a7a7f38e93.png

带样式的字符串元素Styled String Element

StyledStringElement允许使用内置表格单元样式或自定义格式来显示字符串。A StyledStringElement allows strings to be presented using either built-in table cell styles or with custom formatting.

3077a3b20ec5ecbd6b8531c6e00ef222.png3077a3b20ec5ecbd6b8531c6e00ef222.png

StyledStringElement类派生自 StringElement ,但允许开发人员自定义一些属性,如字体、文本颜色、背景单元颜色、换行模式、要显示的行数,以及是否应显示附件。The StyledStringElement class derives from StringElement, but lets developers customize a handful of properties like the Font, text color, background cell color, line breaking mode, number of lines to display, and whether an accessory should be displayed.

多行元素Multiline Element

4f009e382c25e4a0f1f757f2b987c7e3.png4f009e382c25e4a0f1f757f2b987c7e3.png

Entry 元素Entry Element

EntryElement正如名称所示,用于获取用户输入。The EntryElement, as the name implies, is used to get user input. 它支持常规字符串或密码(其中隐藏了个字符)。It supports either regular strings or passwords, where characters are hidden.

9e1dc9055d5790ef1056c5c915a29bd1.png9e1dc9055d5790ef1056c5c915a29bd1.png

它初始化为三个值:It is initialized with three values:

将向用户显示的项的标题。The caption for the entry that will be shown to the user.

占位符文本 (这是向用户) 提供提示的灰色文本。Placeholder text (this is the greyed-out text that provides a hint to the user).

文本的值。The value of the text.

占位符和值可以为 null。The placeholder and value can be null. 但标题是必需的。However, the caption is required.

在任何时候,访问其 Value 属性都可以检索的值 EntryElement 。At any point, accessing its Value property can retrieve the value of the EntryElement.

此外,还 KeyboardType 可以在创建时将属性设置为数据输入所需的键盘类型样式。Additionally the KeyboardType property can be set at creation time to the keyboard type style desired for the data entry. 此操作可用于使用如下所示的值配置键盘 UIKeyboardType :This can be used to configure the keyboard using the values of UIKeyboardType as listed below:

NumericNumeric

电话Phone

UrlUrl

电子邮件Email

Boolean 元素Boolean Element

34511956c2910e65a660f7fc428035e3.png34511956c2910e65a660f7fc428035e3.png

Checkbox 元素Checkbox Element

7f6b0ee89afd3c1ebfc0ff8b90b61d41.png7f6b0ee89afd3c1ebfc0ff8b90b61d41.png

单选元素Radio Element

RadioElement需要 RadioGroup 在中指定 RootElement 。A RadioElement requires a RadioGroup to be specified in the RootElement.

mtRoot = new RootElement ("Demos", new RadioGroup("MyGroup", 0));

70b31e0e3ab6b9c49437f97815064132.png70b31e0e3ab6b9c49437f97815064132.png

RootElements 还用于协调收音机元素。RootElements are also used to coordinate radio elements. RadioElement成员可以跨多个节 (例如,实现类似于响铃音选择器的内容,并将系统铃声) 中的自定义铃声分隔开。The RadioElement members can span multiple Sections (for example to implement something similar to the ring tone selector and separate custom ring tones from system ringtones). "摘要" 视图将显示当前选中的单选元素。The summary view will show the radio element that is currently selected. 为此,请使用 RootElement 组构造函数创建,如下所示:To use this, create the RootElement with the group constructor, like this:

var root = new RootElement ("Meals", new RadioGroup ("myGroup", 0));

中组的名称 RadioGroup 用于显示 "包含" 页中的选定值 (如果任何) 和值(在本例中为零)是第一个选定项的索引。The name of the group in RadioGroup is used to show the selected value in the containing page (if any) and the value, which is zero in this case, is the index of the first selected item.

徽章元素Badge Element

313a07d219591716f13ffaa0285b8d42.png313a07d219591716f13ffaa0285b8d42.png

Float 元素Float Element

407cec8455485234fdf34b1eb1a802d1.png407cec8455485234fdf34b1eb1a802d1.png

活动元素Activity Element

84058d094185afc4ec15b13333ebeb9c.png84058d094185afc4ec15b13333ebeb9c.png

Date 元素Date Element

2ee8d327e84f9d5590dbc7c495053cd2.png

选择对应于 DateElement 的单元格时,将显示日期选取器,如下所示:When the cell corresponding to the DateElement is selected, a date picker is presented as shown below:

649ec5eebb35981c8eadf7e9147aca7b.png649ec5eebb35981c8eadf7e9147aca7b.png

Time 元素Time Element

8c8098850ea278e8213a7a503c4bd849.png8c8098850ea278e8213a7a503c4bd849.png

如果选择对应于 TimeElement 的单元格,则会显示时间选取器,如下所示:When the cell corresponding to the TimeElement is selected, a time picker is presented as shown below:

7b989eb6d2f4290c27046ff683c9262d.png7b989eb6d2f4290c27046ff683c9262d.png

DateTime 元素DateTime Element

0a0533d3d3c0656f6a518a44b92435a7.png0a0533d3d3c0656f6a518a44b92435a7.png

选择对应于 DateTimeElement 的单元格时,将显示日期时间选取器,如下所示:When the cell corresponding to the DateTimeElement is selected, a datetime picker is presented as shown below:

c97ab54b52fd85759a1bdf999d15b920.pngc97ab54b52fd85759a1bdf999d15b920.png

HTML 元素HTML Element

533f54c6cac8f9f0dc1f2b95da1184f1.png533f54c6cac8f9f0dc1f2b95da1184f1.png

在 HTMLElement Caption 表单元中显示其属性的值。The HTMLElement displays the value of its Caption property in the table cell. 选择 Whe 后,将在 Url 控件中加载分配给该元素的,如下 UIWebView 所示:Whe selected, the Url assigned to the element is loaded in a UIWebView control as shown below:

92b303d5f4488bada3f0f6b86420b7a1.png92b303d5f4488bada3f0f6b86420b7a1.png

Message 元素Message Element

738435f332f6714bee9966d41311762a.png738435f332f6714bee9966d41311762a.png

加载更多元素Load More Element

使用此元素可允许用户在列表中加载更多项。Use this element to allow users to load more items in your list. 您可以自定义标准和加载标题以及字体和文本颜色。You can customize the normal and loading captions, as well as the font and text color.

UIActivity指示器开始进行动画处理,当用户点击单元格时,将显示加载标题,并 NSAction 执行传入构造函数的。The UIActivity indicator starts animating, and the loading caption is displayed when a user taps the cell, and then the NSAction passed into the constructor is executed. 完成中的代码后 NSAction , UIActivity 指示器将停止动画并再次显示正常标题。Once your code in the NSAction is finished, the UIActivity indicator stops animating and the normal caption is displayed again.

UIView 元素UIView Element

此外, UIView 可以使用来显示任何自定义 UIViewElement 。Additionally, any custom UIView can be displayed using the UIViewElement.

所有者描述的元素Owner-Drawn Element

此元素必须是子类,因为它是抽象类。This element must be subclassed as it is an abstract class. 应该重写 Height(RectangleF bounds) 方法,应在该方法中返回元素的高度,以及 Draw(RectangleF bounds, CGContext context, UIView view) 在给定边界内使用上下文和视图参数执行所有自定义绘图的方法。You should override the Height(RectangleF bounds) method in which you should return the height of the element, as well as Draw(RectangleF bounds, CGContext context, UIView view) in which you should do all your customized drawing within the given bounds, using the context and view parameters. 此元素执行的是子类 a 的繁重提升 UIView ,并将其放在要返回的单元中,只需实现两个简单的重写。This element does the heavy lifting of subclassing a UIView, and placing it in the cell to be returned, leaving you only needing to implement two simple overrides. 可以在文件的示例应用中查看更好的示例实现 DemoOwnerDrawnElement.cs 。You can see a better sample implementation in the sample app in the DemoOwnerDrawnElement.cs file.

下面是实现类的一个非常简单的示例:Here's a very simple example of implementing the class:

public class SampleOwnerDrawnElement : OwnerDrawnElement

{

public SampleOwnerDrawnElement (string text) : base(UITableViewCellStyle.Default, "sampleOwnerDrawnElement")

{

this.Text = text;

}

public string Text { get; set; }

public override void Draw (RectangleF bounds, CGContext context, UIView view)

{

UIColor.White.SetFill();

context.FillRect(bounds);

UIColor.Black.SetColor();

view.DrawString(this.Text, new RectangleF(10, 15, bounds.Width - 20, bounds.Height - 30), UIFont.BoldSystemFontOfSize(14.0f), UILineBreakMode.TailTruncation);

}

public override float Height (RectangleF bounds)

{

return 44.0f;

}

}

JSON 元素JSON Element

JsonElement是的一个子类 RootElement ,它扩展了 RootElement 以便能够从本地或远程 url 加载嵌套子元素的内容。The JsonElement is a subclass of RootElement that extends a RootElement to be able to load the contents of nested child from a local or remote url.

JsonElement是 RootElement 可在两种形式中实例化的。The JsonElement is a RootElement that can be instantiated in two forms. 一个版本创建 RootElement 将按需加载内容的。One version creates a RootElement that will load the contents on demand. 这些是通过使用 JsonElement 在末尾使用额外自变量的构造函数创建的,从其加载内容的 url:These are created by using the JsonElement constructors that take an extra argument at the end, the url to load the contents from:

var je = new JsonElement ("Dynamic Data", "https://tirania.org/tmp/demo.json");

另一种形式将从本地文件或 System.Json.JsonObject 已分析的现有创建数据:The other form creates the data from a local file or an existing System.Json.JsonObject that you have already parsed:

var je = JsonElement.FromFile ("json.sample");

using (var reader = File.OpenRead ("json.sample"))

return JsonElement.FromJson (JsonObject.Load (reader) as JsonObject, arg);

有关将 JSON 与 MT 一起使用的详细信息。D. 参阅 JSON 元素演练 教程。For more information on using JSON with MT.D, see the JSON Element Walkthrough tutorial.

其他功能Other Features

请求刷新支持Pull-to-Refresh Support

请求**刷新是最初在Tweetie2应用中找到的视觉效果,在许多应用程序中,这会成为一种流行的效果。Pull-to- Refresh is a visual effect originally found in the Tweetie2 app, which became a popular effect among many applications.

若要向对话添加自动请求刷新支持,只需执行以下两项操作:挂钩事件处理程序,以便在用户提取数据时得到通知,并在加载数据后通知 DialogViewController 其默认状态。To add automatic pull-to-refresh support to your dialogs, you only need to do two things: hook up an event handler to be notified when the user pulls the data and notify the DialogViewController when the data has been loaded to go back to its default state.

将通知挂钩很简单;只需连接到 RefreshRequested 上的事件 DialogViewController ,如下所示:Hooking up a notification is simple; just connect to the RefreshRequested event on the DialogViewController, like this:

dvc.RefreshRequested += OnUserRequestedRefresh;

然后,在您的方法 OnUserRequestedRefresh 中,将对某些数据加载进行排队,请求从 net 请求某些数据,或旋转线程以计算数据。Then on your method OnUserRequestedRefresh, you would queue some data loading, request some data from the net, or spin a thread to compute the data. 加载数据后,必须通知 DialogViewController 新数据所在,并将视图还原到其默认状态,方法是调用 ReloadComplete :Once the data has been loaded, you must notify the DialogViewController that the new data is in, and to restore the view to its default state, you do this by calling ReloadComplete:

dvc.ReloadComplete ();

搜索支持Search Support

若要支持搜索,请 EnableSearch 在上设置属性 DialogViewController 。To support searching, set the EnableSearch property on your DialogViewController. 还可以将属性设置 SearchPlaceholder 为在搜索栏中用作水印文本。You can also set the SearchPlaceholder property to use as the watermark text in the search bar.

搜索将在用户键入时更改视图的内容。Searching will change the contents of the view as the user types. 它会搜索可见字段并向用户显示这些字段。It searches the visible fields and shows those to the user. DialogViewController公开了三种方法,以编程方式启动、终止或触发针对结果的新筛选器操作。The DialogViewController exposes three methods to programmatically initiate, terminate or trigger a new filter operation on the results. 下面列出了这些方法:These methods are listed below:

StartSearch

FinishSearch

PerformFilter

系统是可扩展的,因此,如果需要,可以更改此行为。The system is extensible, so you can alter this behavior if you want.

正在加载背景图像Background Image Loading

Monotouch.dialog 包含 TweetStation 应用程序的映像加载程序。MonoTouch.Dialog incorporates the TweetStation application’s image loader. 此图像加载程序可用于在后台加载图像,支持缓存并可在加载映像时通知代码。This image loader can be used to load images in the background, supports caching and can notify your code when the image has been loaded.

它还会限制传出的网络连接数。It will also limit the number of outgoing network connections.

在类中实现了图像加载程序 ImageLoader ,你只需调用 DefaultRequestImage 方法,你将需要提供要加载的映像的 Uri,以及在 IImageUpdated 加载映像时将调用的接口的一个实例。The image loader is implemented in the ImageLoader class, all you need to do is call the DefaultRequestImage method, you will need to provide the Uri for the image you want to load, as well as an instance of the IImageUpdated interface which will be invoked when the image has been loaded.

例如,以下代码将图像从 Url 加载到中 BadgeElement :For example the following code loads an image from a Url into a BadgeElement:

string uriString = "http://some-server.com/some image url";

var rootElement = new RootElement("Image Loader") {

new Section() {

new BadgeElement( ImageLoader.DefaultRequestImage( new Uri(uriString), this), "Xamarin")

}

};

ImageLoader 类公开了一个清除方法,当你想要释放当前缓存在内存中的所有图像时,你可以调用此方法。The ImageLoader class exposes a Purge method that you can call when you want to release all of the images that are currently cached in memory. 当前代码具有50图像的缓存。The current code has a cache for 50 images. 如果要使用不同的缓存大小 (例如,如果希望图像太大,以致50映像太大) ,则只需创建 ImageLoader 的实例,并传递要保存在缓存中的映像数。If you want to use a different cache size (for instance, if you are expecting the images to be too large that 50 images would be too much), you can just create instances of ImageLoader and pass the number of images you want to keep in the cache.

使用 LINQ 创建元素层次结构Using LINQ to Create Element Hierarchy

通过使用 LINQ 和 c # 的初始化语法,LINQ 可用于创建元素层次结构。Via the clever usage of LINQ and C#’s initialization syntax, LINQ can be used to create an element hierarchy. 例如,下面的代码从某些字符串数组创建一个屏幕,并通过传递到每个的匿名函数来处理单元格选择 StringElement :For example, the following code creates a screen from some string arrays and handles cell selection via an anonymous function that is passed into each StringElement:

var rootElement = new RootElement ("LINQ root element") {

from x in new string [] { "one", "two", "three" }

select new Section (x) {

from y in "Hello:World".Split (':')

select (Element) new StringElement (y, delegate { Debug.WriteLine("cell tapped"); })

}

};

这可以轻松地与 XML 数据存储或数据库中的数据结合使用,几乎可以完全从数据创建复杂的应用程序。This could easily be combined with an XML data store or data from a database to create complex applications nearly entirely from data.

扩展 MT。2-dExtending MT.D

创建自定义元素Creating Custom Elements

您可以通过从现有元素继承或通过从根类元素派生来创建自己的元素。You can create your own element by inheriting from either an existing Element or by deriving from the root class Element.

若要创建自己的元素,需要重写以下方法:To create your own Element, you will want to override the following methods:

// To release any heavy resources that you might have

void Dispose (bool disposing);

// To retrieve the UITableViewCell for your element

// you would need to prepare the cell to be reused, in the

// same way that UITableView expects reusable cells to work

UITableViewCell GetCell (UITableView tv);

// To retrieve a "summary" that can be used with

// a root element to render a summary one level up.

string Summary ();

// To detect when the user has tapped on the cell

void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path);

// If you support search, to probe if the cell matches the user input

bool Matches (string text);

如果元素的大小可以是可变的,则需要实现 IElementSizing 接口,该接口包含一个方法:If your element can have a variable size, you need to implement the IElementSizing interface, which contains one method:

// Returns the height for the cell at indexPath.Section, indexPath.Row

float GetHeight (UITableView tableView, NSIndexPath indexPath);

如果你打算 GetCell 通过调用 base.GetCell(tv) 并自定义返回的单元格来实现方法,则还需要重写 CellKey 属性以返回将对你的元素唯一的键,如下所示:If you are planning on implementing your GetCell method by calling base.GetCell(tv) and customizing the returned cell, you need to also override the CellKey property to return a key that will be unique to your Element, like this:

static NSString MyKey = new NSString ("MyKey");

protected override NSString CellKey {

get {

return MyKey;

}

}

这适用于大多数元素,但不适用于 StringElement 和, StyledStringElement 因为它们对各种呈现方案使用自己的键集。This works for most elements, but not for the StringElement and StyledStringElement as those use their own set of keys for various rendering scenarios. 必须复制这些类中的代码。You would have to replicate the code in those classes.

DialogViewControllers (DVCs)DialogViewControllers (DVCs)

反射和元素 API 使用相同的 DialogViewController 。Both the Reflection and the Elements API use the same DialogViewController. 有时你需要自定义视图的外观,或者你可能想要使用的某些功能 UITableViewController 超出了 ui 的基本创建功能。Sometimes you will want to customize the look of the view or you might want to use some features of the UITableViewController that go beyond the basic creation of UIs.

DialogViewController只是的子类 UITableViewController ,你可以采用与自定义相同的方式对其进行自定义 UITableViewController 。The DialogViewController is merely a subclass of the UITableViewController and you can customize it in the same way that you would customize a UITableViewController.

例如,如果要将列表样式更改为 Grouped 或 Plain ,则可以通过在创建控制器时更改属性来设置此值,如下所示:For example, if you wanted to change the list style to be either Grouped or Plain, you could set this value by changing the property when you create the controller, like this:

var myController = new DialogViewController (root, true) {

Style = UITableViewStyle.Grouped;

}

对于更高级的自定义 DialogViewController 设置,如设置其背景,你会将它划分为子类并重写适当的方法,如以下示例中所示:For more advanced customizations of the DialogViewController, such as setting its background, you would subclass it and override the proper methods, as shown in the example below:

class SpiffyDialogViewController : DialogViewController {

UIImage image;

public SpiffyDialogViewController (RootElement root, bool pushing, UIImage image)

: base (root, pushing)

{

this.image = image;

}

public override LoadView ()

{

base.LoadView ();

var color = UIColor.FromPatternImage(image);

TableView.BackgroundColor = UIColor.Clear;

ParentViewController.View.BackgroundColor = color;

}

}

另一个自定义点是中的以下虚拟方法 DialogViewController :Another customization point is the following virtual methods in the DialogViewController:

public override Source CreateSizingSource (bool unevenRows)

如果单元格大小相等,则此方法应返回的子类 DialogViewController.Source ; DialogViewController.SizingSource 如果单元格不相等,则返回的子类。This method should return a subclass of DialogViewController.Source for cases where your cells are evenly sized, or a subclass of DialogViewController.SizingSource if your cells are uneven.

您可以使用此替代来捕获任何 UITableViewSource 方法。You can use this override to capture any of the UITableViewSource methods. 例如, TweetStation 使用它来跟踪用户滚动到顶部的时间,并相应地更新未读推文的数量。For example, TweetStation uses this to track when the user has scrolled to the top and update accordingly the number of unread tweets.

验证Validation

元素不会自行提供验证,因为这种模型非常适合于网页和桌面应用程序,也不会直接映射到 iPhone 交互模型。Elements do not provide validation themselves as the models that are well suited for web pages and desktop applications do not map directly to the iPhone interaction model.

如果要进行数据验证,则应在用户使用输入的数据触发操作时执行此操作。If you want to do data validation, you should do this when the user triggers an action with the data entered. 例如,在顶部工具栏上的 " 完成 " 或 " 下一步 " 按钮,或者某些按钮 StringElement 用于执行下一阶段。For example a Done or Next button on the top toolbar, or some StringElement used as a button to go to the next stage.

在这种情况下,你将执行基本输入验证,并且可能更复杂的验证,例如检查与服务器的用户/密码组合的有效性。This is where you would perform basic input validation, and perhaps more complicated validation like checking for the validity of a user/password combination with a server.

如何将错误通知用户是特定于应用程序的。How you notify the user of an error is application specific. 您可以弹出 UIAlertView 或显示提示。You could pop up a UIAlertView or show a hint.

总结Summary

本文介绍了有关 Monotouch.dialog 的许多信息。This article covered a lot of information about MonoTouch.Dialog. 它讨论了 MT 的基本原理。D 工作,并涵盖了包含 MT. D 的各种组件。It discussed the fundamentals of the how MT.D works and covered the various components that comprise MT.D. 它还展示了 MT 支持的各种元素和表自定义。D 并讨论了 MT 的方式。可以通过自定义元素扩展 D。It also showed the wide array of elements and table customizations supported by MT.D and discussed how MT.D can be extended with custom elements. 此外,它还说明了 MT 中的 JSON 支持。D:允许从 JSON 动态创建元素。Additionally it explained the JSON support in MT.D that allows creating elements dynamically from JSON.

相关链接Related Links

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值