UITextField 光标的位置设置获取 2014-01-02 08:59 14368人阅读 评论(5) 收藏 举报 分类: ios Extent(1) 版权声明:本文为博主原创文章,未经博主允许不得转载。 UITextField 光标的位置设置获取 通过给UITextField 加一个拓展 [objc] view plain copy print ? //#import "UITextField+ExtentRange.h" [objc] view plain copy print ? #import <UIKit/UIKit.h> @interface UITextField (ExtentRange) - (NSRange) selectedRange; - (void) setSelectedRange:(NSRange) range; @end [objc] view plain copy print ? // #import "UITextField+ExtentRange.m" [objc] view plain copy print ? #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