iOS上的自定义键盘:如何访问UITextField? [英] Custom Keyboard on iOS: How do I access the UITextField?

查看:101
本文介绍了iOS上的自定义键盘:如何访问UITextField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIView 子类,我将其分配给文本字段,如下所示:

I have a UIView subclass that I assign to a text field as follows:

self.textField.inputView = [[HexKeyboard alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

这是有效的(即键盘出现)。 但是, HexKeyboard 实例应如何知道 textField

and this works (i.e., the keyboard comes up). However, how should the HexKeyboard instance know about the textField?

[当然我可以在 HexKeyboard 中添加一个属性来实现这一点(并称之为 delegate ),但我认为这里有一个内置机制...]

[Of course I can add a property to the HexKeyboard to achieve this (and call it delegate), but I figure there's a built-in mechanism for this...]

推荐答案

似乎正如其他回答者所指出的那样,没有内置的机制。正如Nick所说,你不需要复杂的委托模式。或者更确切地说,您使用委托模式,但您可以免费获得委托类。在这种情况下,它是 UITextInput 协议。

There seems to be no built-in mechanism for this, as the other answerers have pointed out. As Nick says, you don't need a complex delegate pattern for this. Or rather, you use the delegate pattern, but you get the delegate class for free. In this case it's the UITextInput protocol.

所以你的键盘可能看起来像这样(并且有一个NIB)

So your keyboard probably looks like this (and has a NIB)

@interface ViewController : UIViewController

// use assign if < iOS 5
@property (nonatomic, weak) IBOutlet id <UITextInput> *delegate;

@end

创建键盘控制器时,指定 UITextInput conformer to it,如下所示:

When you create the keyboard controller, you assign the UITextInput conformer to it, so something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    HexKeyboardController *keyboardController = [[HexKeyboardController alloc] initWithNibName:@"HexKeyboardController" bundle:nil];
    self.textField.inputView = keyboardController.view;
    keyboardController.delegate = self.textField;

}

然而,我想,必须有一种方法来定义这个键盘只需一次,让键盘自动知道召唤它的 UITextInput 对象是谁。但我一直无所顾忌......你无法弄清楚 firstResponder 是谁,除非你自己试图查看层次结构或将你的代表留在列表中(这会导致保留循环)。 另外,这并不是很糟糕,因为当 textField 被解除分配时,HexKeyboardController也会卸载。

However, I thought, there MUST be a way to define this keyboard just once and get the keyboard to "automatically know" who the UITextInput object that summoned it is. But I've looked around to no avail... you cannot figure out who the firstResponder is unless you troll the view hierarchy yourself or retain your delegates in a list (which would cause a retain loop). Plus, this isn't so bad because the HexKeyboardController will unload, too, when the textField is dealloced.

这篇关于iOS上的自定义键盘:如何访问UITextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆