iOS上的自定义键盘:如何访问UITextField?
我有一个UIView
子类,我分配给一个文本字段如下:
self.textField.inputView = [[HexKeyboard alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
这个工程(即键盘出现)。 但是, HexKeyboard
实例应该如何知道textField
?
[当然,我可以添加一个属性到HexKeyboard
来实现这个(并称之为delegate
),但我认为这是一个内置的机制…]
你并不需要一个复杂的委托模式。 只要在你的HexKeyboard类上创build一个types为UITextField的属性,并将其设置为unsafe_unretained引用,这样你就不会得到一个保留循环:
@interface HexKeyboard @property (nonatomic, unsafe_unretained) UITextField *textField; @end
然后在设置inputView时设置它:
self.textField.inputView = [[HexKeyboard alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; self.textField.inputView.textField = self.textField;
其他答复者指出,似乎没有这个机制。 正如尼克所说,你不需要一个复杂的委托模式。 或者说,您使用委托模式,但您可以免费获得委托类。 在这种情况下,它是UITextInput
协议。
所以你的键盘可能看起来像这样(并有一个NIB)
@interface ViewController : UIViewController // use assign if < iOS 5 @property (nonatomic, weak) IBOutlet id <UITextInput> *delegate; @end
在创build键盘控制器时,将UITextInput
赋值给它,所以如下所示:
- (void)viewDidLoad { [super viewDidLoad]; HexKeyboardController *keyboardController = [[HexKeyboardController alloc] initWithNibName:@"HexKeyboardController" bundle:nil]; self.textField.inputView = keyboardController.view; keyboardController.delegate = self.textField; }
然而,我想,必须有一种方法来定义这个键盘只是一次,让键盘“自动知道”谁召唤它的UITextInput
对象。 但是,我已经环顾四周无济于事了,除非你自己firstResponder
视图层次结构,或者将你的委托保留在列表中(这将导致保留循环),否则你无法弄清楚第一个firstResponder
是谁。 另外,这并不是那么糟糕,因为当textField
被处理时,HexKeyboardController也会被卸载。
我不相信有一个内置的机制,你可能需要在hex键盘的委托,将接收到“击键”,然后将其附加到文本字段,或无论你需要做的..