如何在不打字的情况下检测 UITextField 光标移动?

TPW*_*ang 2 xcode objective-c uitextfield ios uitextfielddelegate

当用户仅移动光标而不输入新单词(即(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange) replacementString:(NSString *)string不被触发)时,如何检测此事件?

小智 6

在viewDidAppear中添加selectedTextRange属性观察者,

[self.txtfield addObserver:self forKeyPath:@"selectedTextRange" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld  context:nil];
Run Code Online (Sandbox Code Playgroud)

然后为这个属性添加函数,

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

当您移动光标而不输入任何文本时,它应该打印“光标已移动”。