IOS custom keyboard: how do I access a UITextField?

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

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

and it works (i.e. the keyboard is suitable). However, how should a HexKeyboard instance of textField ?

[Of course, I can add a property to HexKeyboard to achieve this (and call it delegate ), but I believe that a mechanism is built in for this ...]

+4
source share
3 answers

There seems to be no built-in mechanism for this, as other defendants have pointed out. As Nick says, you don’t need a complicated delegation template for this. Rather, you use the delegate template, but you get the delegate class for free. In this case, this is the UITextInput protocol.

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 

When you create a keyboard controller, you assign it a UITextInput connector, something like this:

 - (void)viewDidLoad { [super viewDidLoad]; HexKeyboardController *keyboardController = [[HexKeyboardController alloc] initWithNibName:@"HexKeyboardController" bundle:nil]; self.textField.inputView = keyboardController.view; keyboardController.delegate = self.textField; } 

However, I thought that there MUST be a way to detect this keyboard only once and make the keyboard "automatically know" who called its UITextInput object. But I looked around to no avail ... you cannot understand who the firstResponder is unless you troll the view hierarchy yourself or save your delegates in a list (which will cause a save loop). Also, this is not so bad because the HexKeyboardController is also unloaded when the textField freed.

+1
source

You do not need a complex delegation template for this. Just create a property of type UITextField in your HexKeyboard class and make it an unsafe_unretained reference so you don't get a save loop:

 @interface HexKeyboard @property (nonatomic, unsafe_unretained) UITextField *textField; @end 

Then install it when you install inputView:

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

I do not believe that there is a built-in mechanism for this, you probably want the delegate on the hexadecimal keyboard to receive β€œkeystrokes” from him, and then add it to the text box or something else that you need to do ..

0
source

All Articles