普通的光标移动,点键盘的删除键,会从最后一位删除,加一UITextField的分类即可
#import <UIKit/UIKit.h> @interface UITextField (ExtentRange) - (NSRange) selectedRange; - (void) setSelectedRange:(NSRange) range; @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 // 备注:UITextField必须为第一响应者才有效 { 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