简体   繁体   English

iOS:如何将密钥发送到 UITextField?

[英]iOS: How to send key to UITextField?

I have implemented a custom keyboard view in an iOS application.我在 iOS 应用程序中实现了自定义键盘视图。 I have several UITextFields that use this keyboard.我有几个使用这个键盘的 UITextFields。 Some of these UITextFields have delegates that override shouldChangeCharactersInRange .其中一些 UITextField 具有覆盖shouldChangeCharactersInRange的委托。 However if my keyboard just sets the text value in the text field, the shouldChangeCharactersInRange message is not sent.但是,如果我的键盘只是在文本字段中设置文本值,则不会发送 shouldChangeCharactersInRange 消息。 What I think I need is to actually do something like SendKey and send the key code to the UITextField.我认为我需要的是实际执行类似 SendKey 的操作并将密钥代码发送到 UITextField。

Any suggestions?有什么建议么?

As I note in my answer here , the UITextField conforms to the UITextInput protocol.正如我在此处的回答中所指出的UITextField符合UITextInput协议。 So you call its methods:所以你调用它的方法:

[textField replaceRange:textField.selectedTextRange withText:text];

Of interest: "" will perform a backspace and, of course, " " will do a space.有趣的是: ""将执行退格,当然, " "将执行空格。

This should call the shouldChangeCharactersInRange method automatically.这应该会自动调用shouldChangeCharactersInRange方法。 If not, you'd have to do that yourself.如果没有,你必须自己做。

You definitely need to do this if you are going to create a custom keyboard on iOS.如果您要在 iOS 上创建自定义键盘,您肯定需要这样做。

It sounds like the keyboard is responsible for sending the shouldChangeCharactersInRange message to the UITextField itself, rather than just setting its value.听起来键盘负责将 shouldChangeCharactersInRange 消息发送到 UITextField 本身,而不仅仅是设置其值。 Have your keyboard compute the values of range and string , and call:让你的键盘计算rangestring的值,然后调用:

if ([[theTextField delegate] textField:theTextField shouldChangeCharactersInRange:range replacementString:string])
    theTextField.text = [theTextField.text stringByReplacingCharactersInRange:range withString:string];

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

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