Custom Keyboard on iOS: How do I access the UIText

2020-04-08 03:18发布

问题:

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)];

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

[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...]

回答1:

You don't really need a complex delegate pattern for this. Just create a property of type UITextField on your HexKeyboard class, and make it an unsafe_unretained reference so you don't get a retain loop:

@interface HexKeyboard

@property (nonatomic, unsafe_unretained) UITextField *textField;

@end

Then set it when you set your inputView:

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


回答2:

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.

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 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;

}

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.



回答3:

I dont believe there is a built in mechanism for this, you probably want the a delegate in the hex keyboard that will receive the "keystrokes" from it and then append it to the textfield, or whatever it is you need to do..