2

When a user only moves the cursor without typing a new word (i.e. (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange) replacementString:(NSString *)string does not get triggered), how do I detect this event?

TPWang
  • 1,322
  • 4
  • 20
  • 39

3 Answers3

6

Add selectedTextRange property observer in viewDidAppear,

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

Then add function for this property,

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

When you move the cursor without typing any text it should print "cursor moved".

Dipankar Das
  • 672
  • 5
  • 9
1

There is a selectedTextRange property in UITextField adopted from UITextInput protocol. So you can either subscribe to changes of this property with KVO or implement your own subclass with the method setSelectedTextRange overridden.

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
0

I am sure too sure that is any native delegate of UITextField for cursor movements but you can subclass UITextField and can override method

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let selectedRange = textField.selectedTextRange {

        let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)

        print("\(cursorPosition)")
    }
}

and whenever cursor moves then it should be can check get cursor location.

Community
  • 1
  • 1
Azerue
  • 258
  • 6
  • 16