UITextField -- 观察 selectedTextRange 的变化? [英] UITextField -- observe changes to selectedTextRange?

查看:26
本文介绍了UITextField -- 观察 selectedTextRange 的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法观察 UITextField 的 selectedTextRange 的变化?

Is there any way to observe changes to the selectedTextRange of a UITextField?

我尝试观察所有 UIControlEvents.但是更改 selectedTextRange 不会触发 UIControlEvent.

I tried observing all UIControlEvents. But changing the selectedTextRange does not trigger a UIControlEvent.

另一个死胡同——UIKit 类不符合 KVO.

Another dead end -- UIKit classes are not KVO compliant.

然后是 UITextFieldTextDidChangeNotification.但这是对文本的更改.

Then there is the UITextFieldTextDidChangeNotification. But that's for changes to the text.

有什么想法吗?

推荐答案

Subclass UITextField 如下.

Subclass UITextField as follows.

@interface WJTextField : UITextField
@end

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

实施:

@implementation WJTextField

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

@end

然后将 -textFieldDidChangeSelection: 添加到文本字段的委托中.

Then add -textFieldDidChangeSelection: to your text field's delegate.

警告:只有在移动光标时才会发送此委托消息,在键入或粘贴文本时不会发送,对于您必须实现的那些事件textField:shouldChangeCharactersInRange:replacementString:,其中选择范围将被设置为range.location + [string length](如果您返回YES) 或保持不变(如果您返回 NO).

Caveat: This delegate message will be sent only when the cursor is moved, it will not be sent when typing or pasting text, for those events you have to implement textField:shouldChangeCharactersInRange:replacementString:, where the selection range is going to either be set to range.location + [string length] (if you return YES) or remain the same (if you return NO).

这篇关于UITextField -- 观察 selectedTextRange 的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆