1

I am facing a problem regarding cursor move. I have applied below solution and it is not working:

In ViewController.h file

@interface ViewController : UIViewController<WJTextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@end

In ViewController.m file,

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) textFieldDidChangeSelection:(UITextField *)textField
{
    NSLog(@"Function is hit");
}

@end

Subclass UITextField as follows.

@interface WJTextField : UITextField
@end

@protocol WJTextFieldDelegate <UITextFieldDelegate>
- (void) textFieldDidChangeSelection: (UITextField *) textField;
@end

Implementation:

@implementation WJTextField

- (void) setSelectedTextRange: (UITextRange *) selectedTextRange
{
    [super setSelectedTextRange: selectedTextRange];
    if ([self.delegate respondsToSelector: @selector(textFieldDidChangeSelection:)])
        [(id <WJTextFieldDelegate>) self.delegate textFieldDidChangeSelection: self];
}

@end

But it is not hitting textFieldDidChangeSelection callback. Will anyone please help?

Note that, I have checked answer from below link: [UITextField -- observe changes to selectedTextRange?

Community
  • 1
  • 1
Arup Sarker
  • 173
  • 1
  • 9

1 Answers1

3

Finally got solution. It is a simple way to detect selection in textField

add object property observer in viewDidAppear

 [self.keyboardInputFieldPassword addObserver:self forKeyPath:@"selectedTextRange" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld  context:nil];

Then Add observe function for property

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if([keyPath isEqualToString:@"selectedTextRange"] && self.keyboardInputFieldPassword == object)
            [self textFieldDidChangeSelection:self.keyboardInputFieldPassword];
    }

This will capture the selection range in UITextField

For following the convention, you should removeObserver in viewDidDisappear

   [self.keyboardInputFieldPassword removeObserver:self forKeyPath:@"selectedTextRange" context:nil];
Arup Sarker
  • 173
  • 1
  • 9