先来一个分类
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITextField (ExtentRange)
- (NSRange)selectedRange;
- (void)setSelectedRange:(NSRange)range;
@end
NS_ASSUME_NONNULL_END
#import "UITextField+ExtentRange.h"
@implementation UITextField (ExtentRange)
- (NSRange) selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void) setSelectedRange:(NSRange) range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
使用和监听
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "UITextField+ExtentRange.h"
@interface ViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *textFiled;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, 200, 100)];
self.textFiled.backgroundColor = [UIColor redColor];
self.textFiled.delegate = self;
[self.view addSubview:self.textFiled];
}
- (void)textFieldDidChangeSelection:(UITextField *)textField{
NSLog(@"位置%lu长度%lu",(unsigned long)textField.selectedRange.location,(unsigned long)textField.selectedRange.length);
}
@end