// 内容为[start,end),无论是否有选取区域,start都描述了光标的位置。 @property (nullable, readwrite, copy) UITextRange *selectedTextRange; // 文首和文尾的位置 @property (nonatomic, readonly) UITextPosition *beginningOfDocument; @property (nonatomic, readonly) UITextPosition *endOfDocument;
// 获取以from为基准的to的偏移,例如abcde,光标在c后,则光标相对文尾的偏移为-2。 - (NSInteger)offsetFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)toPosition; // 获取以from为基准偏移offset的光标位置。 - (nullable UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset; // 创建一个UITextRange - (nullable UITextRange *)textRangeFromPosition:(UITextPosition *)fromPosition toPosition:(UITextPosition *)toPosition;
#import <UIKit/UIKit.h> @interface UITextField (Extension) - (NSInteger)curOffset; - (void)makeOffset:(NSInteger)offset; - (void)makeOffsetFromBeginning:(NSInteger)offset; @end
#import "UITextField+Extension.h"
@implementation UITextField (Extension)
- (NSInteger)curOffset{
// 基于文首计算出到光标的偏移数值。
return [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start];
}
- (void)makeOffset:(NSInteger)offset{
// 实现原理是先获取一个基于文尾的偏移,然后加上要施加的偏移,再重新根据文尾计算位置,最后利用选取来实现光标定位。
UITextRange *selectedRange = [self selectedTextRange];
NSInteger currentOffset = [self offsetFromPosition:self.endOfDocument toPosition:selectedRange.end];
currentOffset += offset;
UITextPosition *newPos = [self positionFromPosition:self.endOfDocument offset:currentOffset];
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
}
- (void)makeOffsetFromBeginning:(NSInteger)offset{
// 先把光标移动到文首,然后再调用上面实现的偏移函数。
UITextPosition *begin = self.beginningOfDocument;
UITextPosition *start = [self positionFromPosition:begin offset:0];
UITextRange *range = [self textRangeFromPosition:start toPosition:start];
[self setSelectedTextRange:range];
[self makeOffset:offset];
}
@end
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有