我遇到有关光标移动的问题。我已经应用了以下解决方案,但它无法正常工作:
在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 -- observe changes to selectedTextRange?
答案 0 :(得分:1)
终于得到了解决方案。这是一种在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
中删除Observer [self.keyboardInputFieldPassword removeObserver:self forKeyPath:@"selectedTextRange" context:nil];