简体   繁体   English

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

[英]How to detect UITextField cursor move without typing?

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

Add selectedTextRange property observer in viewDidAppear,在 viewDidAppear 中添加selectedTextRange属性观察者,

[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".当您移动光标而不输入任何文本时,它应该打印“光标移动”。

There is a selectedTextRange property in UITextField adopted from UITextInput protocol. UITextInput协议采用的UITextField有一个selectedTextRange属性。 So you can either subscribe to changes of this property with KVO or implement your own subclass with the method setSelectedTextRange overridden.因此,您可以使用 KVO 订阅此属性的更改,也可以使用覆盖的方法setSelectedTextRange实现您自己的子类。

I am sure too sure that is any native delegate of UITextField for cursor movements but you can subclass UITextField and can override method我太确定这是用于光标移动的 UITextField 的任何本机委托,但您可以继承 UITextField 并且可以覆盖方法

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.并且每当光标移动时,它应该可以检查获取光标位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM