Search code examples
iosobjective-cxcodeuitextfielduitextfielddelegate

How to detect UITextField cursor move without typing?


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?


Solution

  • 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".