有一个缺点,可以移动光标在尾巴后,如何禁止请指教。
@interface UITextField (Add)
@property (nonatomic, copy) NSString* unitStr;
@end
#import "UITextField+Add.h"
#import <objc/runtime.h>
@implementation UITextField (Add)
-(NSString *)unitStr{
return objc_getAssociatedObject(self, _cmd);
}
-(void)setUnitStr:(NSString *)unitStr{
objc_setAssociatedObject(self, @selector(unitStr), unitStr, OBJC_ASSOCIATION_COPY_NONATOMIC);
if (unitStr.length > 0) {
[self addTarget:self action:@selector(_unitChange:) forControlEvents:UIControlEventEditingChanged];
[self addTarget:self action:@selector(_adjustCursor) forControlEvents:UIControlEventEditingDidBegin];
}else{
[self removeTarget:self action:@selector(_unitChange:) forControlEvents:UIControlEventEditingChanged];
[self removeTarget:self action:@selector(_adjustCursor) forControlEvents:UIControlEventEditingDidBegin];
}
}
#define PreHasValue 1
#define PreNotHasValue 0
-(void)_unitChange:(UITextField *)textfield{
NSString *unitStr = [textfield.unitStr copy];
NSInteger isHasValue = PreNotHasValue;
NSString* realText = nil;
BOOL needAdjustCursor = false;
do {
NSString* text = textfield.text;
if (text.length == 0 || [text isEqualToString:unitStr]) {
break;
}
if (![text containsString:unitStr] && textfield.tag == PreHasValue) {//从最后开始删除
text = [text substringToIndex:text.length-1];
if (text.length == 0) { //数字已经删完
break;
}
}
text = [text stringByReplacingOccurrencesOfString:unitStr withString:@""];
text = [text stringByAppendingString:unitStr];
needAdjustCursor = ![text isEqualToString:textfield.text]; //内容改变,光标位置j就需要调整
isHasValue = PreHasValue;
realText = text;
} while (0);
textfield.tag = isHasValue;
//不相等才执行, 设置值会改变光标位置
if (![textfield.text isEqualToString:realText]) {
textfield.text = realText;
}
if (needAdjustCursor) {
//处理光标
[self _adjustCursor];
}
}
- (void)_adjustCursor
{
NSString *unitStr = [self.unitStr copy];
//处理光标
UITextPosition *selectedPosition = self.endOfDocument;
selectedPosition = [self positionFromPosition:selectedPosition offset:-unitStr.length];
self.selectedTextRange = [self textRangeFromPosition:selectedPosition toPosition:selectedPosition];
}
@end