你好,watchOS – 演练

按照设置和安装中的步骤创建解决方案后,你将获得 3 个项目:

  • iOS 父应用,用于设置或设备上的其他管理任务。 (对于其他类型的 iOS 扩展,这通常称为“容器”应用。)使用手表应用时,用户根本不需要运行父应用就能开始运行手表应用
  • 包含手表应用的程序代码的手表扩展;
  • 手表应用,保存手表上渲染的情节提要和图像资源。

检查引用是否正确:父应用是否具有对手表应用的引用,以及手表应用是否具有对扩展的引用。

确认捆绑包标识符是否遵循 *.watchkitextension *.watchkitapp 约定,以及扩展的 Info.plist 文件的“WKApp 捆绑包 ID”值是否设置为手表应用的捆绑包标识符

现在应该能够运行手表应用,但由于手表应用中的情节提要文件是空白的,因此你无法判断。

双击手表应用中的“Interface.storyboard”以启动 Xamarin iOS 设计器(如果使用的是 Mac,则还可以右键单击“打开方式”并选择“Xcode Interface Builder”

  1. 确保“工具箱”和“属性”面板可见

  2. 单击以选择“接口控制器”;

  3. 将“接口控制器”的“标识符”和“标题”设置为“interfaceController”和“Hi Watch”

  4. 验证“类”是否设置为“InterfaceController”

    Set the Identifier and Title of the Interface Controller to interfaceController and Hi Watch

创建 UI:

  1. 在“工具箱”面板中
  2. 将“按钮”和“标签”拖放到场景中
  3. 如下所示设置控件的文本和属性:
  1. 在“属性”面板中为每个控件设置名称。 在此示例中,我们使用了 myButtonmyLabel

  2. 选择情节提要上的按钮,转到“属性”面板的“事件”列表,然后

  3. 键入 OnButtonPress 并按 Enter 键以创建新的操作。 该操作将显示在列表中,并且 C# 中将自动创建一个部分方法。

The OnButtonPress Action added to a button

保存情节提要后,InterfaceController.designer.cs 会使用控件名称和操作更新。 如果在更新后打开此文件,可以看到 RegisterAttribute 如何与控制器对应,UI 控件如何与用 OutletAttribute 标记的 C# 实例变量对应,以及操作如何映射到用 ActionAttribute 标记的部分方法:

// WARNING
//
// This file has been generated automatically by Visual Studio for Mac from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
[Register ("InterfaceController")]
partial class InterfaceController
{
    [Outlet]
    [GeneratedCode ("iOS Designer", "1.0")]
    WatchKit.WKInterfaceButton myButton { get; set; }

    [Outlet]
    [GeneratedCode ("iOS Designer", "1.0")]
    WatchKit.WKInterfaceLabel myLabel { get; set; }

    [Action ("OnButtonPress:")]
    [GeneratedCode ("iOS Designer", "1.0")]
    partial void OnButtonPress (WatchKit.WKInterfaceButton sender);

    void ReleaseDesignerOutlets ()
    {
        if (myButton != null) {
            myButton.Dispose ();
            myButton = null;
        }
        if (myLabel != null) {
            myLabel.Dispose ();
            myLabel = null;
        }
    }
}

现在打开“InterfaceController.cs”(不是 InterfaceController.designer.cs)并添加以下代码

int clickCount = 0;
partial void OnButtonPress (WatchKit.WKInterfaceButton sender)
{
  var msg = String.Format("Clicked {0} times", ++clickCount);
  myLabel.SetText(msg);
}

此代码应该相当透明:每次调用函数 OnButtonPress 时,实例变量 clickCount 都会递增。 myLabel 的文本已更改以反映此计数;当然,myLabel 是在 XCode 中创建的输出口之一的名称。 partial 函数是与指定的操作名称关联的函数的实现。

如果它还不是启动项目,请执行以下操作:

  1. 右键单击手表扩展项目并选择“设置为启动项目”

  2. 将“部署目标”设置为与 Watch Kit 兼容的模拟器映像(例如 iPhone 6 iOS 8.2);

  3. 按“调试”按钮触发生成和模拟器启动

    The Visual Studio interface elements

当模拟器启动时,请按该按钮以递增标签。 恭喜,你现在拥有了一个手表应用!

The app running in the Simulator