Custom inputView for UITextField , how do I direct input back to the text field?

旧街凉风 提交于 2019-12-29 22:06:17

问题


I have set a custom inputView to my UITextField. I need a way to display the data selected in my custom inputView in the UITextfield. I would like to achieve this the same way the system keyboard does it.

Does anyone know how this is done? How does the system keyboard get a reference to the UITextfield that is the first responder?


回答1:


How does the system keyboard get a reference to the UITextfield that is the first responder?

It just asks the system for the first responder; unfortunately, that's a private UIKit method (or was, last I checked). You can find the first responder by recursing through the view hierarchy and asking each view, but that's pretty clumsy.

Instead, you can add a link to the text field on the input view (I'm assuming your input view is a custom UIView subclass):

@property(nonatomic, assign) UITextField* target;

Then use the UITextField delegate methods in your view controller to see when the text field is being focused:

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if ( [textField.inputView isKindOfClass:[MyInputView class]] )
        ((MyInputView*)textField.inputView).target = textField;
}

- (void)textFieldDidEndEditing:(UITextField*)textField
{
    if ( [textField.inputView isKindOfClass:[MyInputView class]] )
        ((MyInputView*)textField.inputView).target = nil;
}



回答2:


When sending input from your custom input view back to the textfield, note that you can (should) use the UIKeyInput protocol methods that UITextField conforms to. Namely:

- (void)deleteBackward;
- (void)insertText:(NSString *)text;


来源:https://stackoverflow.com/questions/10096979/custom-inputview-for-uitextfield-how-do-i-direct-input-back-to-the-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!