在 Xamarin 中使用 watchOS 文本输入

Apple Watch 不提供键盘供用户输入文本,但支持一些适合手表的替代方案:

  • 从预定义的文本选项列表中选择,
  • Siri 听写,
  • 选择表情符号,
  • 逐字母书写手写识别(在 watchOS 3 中引入)。

模拟器目前不支持听写,但仍可以测试文本输入控制器的其他选项,如“随手写”,如下所示:

Testing the scribble option

若要在手表应用中接受文本输入,请执行以下操作:

  1. 创建预定义选项的字符串数组。
  2. 使用数组调用 PresentTextInputController(无论是否允许表情符号),以及用户完成时调用的 Action
  3. 在完成操作中,测试输入结果并在应用中采取适当的操作(可能设置标签的文本值)。

以下代码片段向用户提供三个预定义的选项:

var suggest = new string[] {"Get groceries", "Buy gas", "Post letter"};

PresentTextInputController (suggest, WatchKit.WKTextInputMode.AllowEmoji, (result) => {
    // action when the "text input" is complete
    if (result != null && result.Count > 0) {
    // this only works if result is a text response (Plain or AllowEmoji)
        enteredText = result.GetItem<NSObject>(0).ToString();
        Console.WriteLine (enteredText);
        // do something, such as myLabel.SetText(enteredText);
    }
});

WKTextInputMode 枚举有三个值:

  • 普通
  • AllowEmoji
  • AllowAnimatedEmoji

普通

设置普通模式后,用户可以选择:

  • 听写,
  • 随手写,或
  • 从应用程序提供的预定义列表中选择。

Dictation, Scribble, or from a pre-defined list that the app supplies

结果始终以 NSObject 形式返回,可以强制转换为 string

表情

有两种类型的表情符号:

  • 常规 Unicode 表情符号
  • 动画图像

当用户选择 Unicode 表情符号时,它将作为字符串返回。

如果选择动画图像表情符号,完成事件处理器中的 result 将包含一个 NSData 对象,其中包含表情符号 UIImage

仅接受听写

若要将用户直接带到听写屏幕而不显示任何建议(或“随手写”选项):

  • 为建议列表传递一个空数组,并
  • 设置 WatchKit.WKTextInputMode.Plain
PresentTextInputController (new string[0], WatchKit.WKTextInputMode.Plain, (result) => {
    // action when the "text input" is complete
    if (result != null && result.Count > 0) {
        dictatedText = result.GetItem<NSObject>(0).ToString();
        Console.WriteLine (dictatedText);
        // do something, such as myLabel.SetText(dictatedText);
    }
});

当用户说话时,手表屏幕将显示以下屏幕,其中包含可理解的文本(例如“This is a test”):

When the user is speaking, the watch screen displays the text as it is understood

按“完成”按钮后,将返回文本