TextView和textField 定位光标问题

有时候需要定位光标位置,但是测试之后发现textField并没有响应方法能监听到光标位置的改变,但是textField可以定义光标位置的变化.

当 有textField需求要监听光标位置变化时,可以利用textView来代替

#import "ViewController.h"

@interface ViewController () <UITextViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 40, 400, 500)];
    
    textView.backgroundColor = [UIColor purpleColor];
    textView.font = [UIFont systemFontOfSize:20];
    textView.delegate = self;
    textView.scrollEnabled = NO;
    [self.view addSubview:textView];
   
    
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    NSLog(@"%ld", textView.selectedRange.location);
}


@end

 实现textView的代理方法即可

原文地址:https://www.cnblogs.com/cdp-snail/p/4911559.html