簡體   English   中英

UITextField —在選擇文本和移動光標期間觀察更改

[英]UITextField — observe changes during text Selection and cursor move

我遇到有關光標移動的問題。 我已經申請了以下解決方案,但無法正常工作:

在ViewController.h文件中

@interface ViewController : UIViewController<WJTextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@end

在ViewController.m文件中,

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) textFieldDidChangeSelection:(UITextField *)textField
{
    NSLog(@"Function is hit");
}

@end

子類UITextField如下。

@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回調。 誰能幫忙嗎?

請注意,我已經從以下鏈接檢查了答案:[ UITextField-觀察對selectedTextRange所做的更改?

終於解決了。 這是在textField中檢測選擇的簡單方法

在viewDidAppear中添加對象屬性觀察器

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

然后為屬性添加觀察功能

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

這將捕獲UITextField中的選擇范圍

為了遵守該約定,您應該在viewDidDisappear中的removeObserver

   [self.keyboardInputFieldPassword removeObserver:self forKeyPath:@"selectedTextRange" context:nil];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM