-->

Problems with protocol imple

2019-05-17 09:43发布

问题:

What I am trying to implement is a UITextField that sees words as characters. Specifically, im trying to see the mathemathical expression sin( as one character for example. I thought to solve this problem by implementing my own UITextInputDelegate. However, the four required functions from this protocol never get called when I implement or adopt this protocol. I tried implementing it in the following ways:

By subclassing a UITextField.

@interface BIDUItextFieldDelegate : UITextField < UITextInputDelegate >

By subclassing a NSObject.

@interface BIDTextfieldInputDelegate : NSObject < UITextInputDelegate >

The corresponding .m file contains:

@implementation BIDTextfieldInputDelegate


- (void)selectionWillChange:(id <UITextInput>)textInput
{
    NSLog(@"sWill");
}

- (void)selectionDidChange:(id <UITextInput>)textInput
{
    NSLog(@"sDid");
}

- (void)textWillChange:(id <UITextInput>)textInput
{
    NSLog(@"tWill");
}

- (void)textDidChange:(id <UITextInput>)textInput
{
    NSLog(@"tDid");
}

For example for the second approach (via subclassing NSObject), I do the following in the (id) init method in an additional custom UITextfield class which is displayed within the app:

//textInputDel is an instance of the custom NSObject class that adopts the above UITextInputDelegate protocol
self.textInputDel = [[BIDTextfieldInputDelegate alloc] init];

self.inputDelegate = self.textFieldDel;

Does anyone know what I am doing wrong, or has a better solution?

回答1:

UITextInputDelegate is not a protocol that you implement; rather, the system creates an object conforming to UITextInputDelegate, and assigns it as the .inputDelegate of a First Responder that conforms to UITextInput.

The methods of UITextInputDelegate are methods for your UITextInput-conforming responder to call on your .inputDelegate to inform it that you have changed your text or selection via means other than keyboard input.