简体   繁体   English

如何在iOS中检测键盘输入?

[英]How to detect keyboard input in iOS?

I have a custom View and I need it to detect text input , like if it was a UITextField . 我有一个自定义View,我需要它来检测文本输入 ,就像它是UITextField

I have seen other questions where people suggest using an "invisible" UITextField to process the input, but this isn't valid for my View, since it's a drawing canvas with at Text Tool that allows the user to enter text. 我看到了其他问题,人们建议使用“不可见” UITextField来处理输入,但这对我的View无效,因为它是带有Text Tool绘图画布 ,允许用户输入文本。

Obviously, having a TextField as helper is really tricky and may interfere with the drawing routine. 显然,使用TextField作为助手确实很棘手,并且可能会干扰绘图例程。

I found out the answer: basically, you have to follow these steps: 我找到了答案:基本上,您必须执行以下步骤:

  1. Add the [Adopts("UIKeyInput")] attribute to you view (adorning the class) [Adopts("UIKeyInput")]属性添加到您的视图中(装饰类)
  2. Make your view implement the UIKeyInput interface 使您的视图实现UIKeyInput接口
  3. override its CanBecomeFirstResponder method to return true . 重写其CanBecomeFirstResponder方法以返回true
  4. You should Implement the InsertText method of the UIKeyInput interface 应该实现UIKeyInput接口的InsertText方法
  5. You can implement the rest of the members of UIKeyInput with the default values (they are mostly enums) and for HasText , you may just return true.to catch the text being typed by the user. 您可以使用默认值(大多数是枚举)实现HasText的其余成员,对于HasText ,您可以只返回true。以捕获用户键入的文本。

With this setup, you just have to call the BecomeFirstResponder method on your view whenever you want your it to start receiving input from the user. 使用此设置,只要您希望视图开始接收来自用户的输入,就只需在视图上调用BecomeFirstResponder方法。

Note: when I talk about "view" I mean the "class" of your view :) 注意:当我谈论“视图”时,是指您的视图的“类” :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM