将来的自己,会感谢现在努力的自己!

0%

TextField标记区选择区

在调试UITextField控件的时候,有时候不得不满足各种奇怪(pa)的需求,因此必须了解各种api。只有掌握了足够的api,才能定制出我们想要的效果(满足各种奇葩需求)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
- (void)resetTextWithNoWhite 
{
NSString * textString = self.text;
NSRange markedRang = [self markedRang];
NSInteger position = markedRang.location;
NSInteger length = markedRang.length;
NSString * markedText = [textString substringWithRange:markedRang];//取出被标记的文字
textString = [textString stringByReplacingCharactersInRange:markedRang withString:@""];//暂时替换掉被标记的文字

NSRange whiteRang = NSMakeRange(0, 0);
whiteRang = [textString rangeOfString:@" "];//找出剩下的文字中空格的位置
while (whiteRang.length > 0) {
textString = [textString stringByReplacingCharactersInRange:whiteRang withString:@""];
if (position > whiteRang.location) {
position = position - whiteRang.length;
}
whiteRang = [textString rangeOfString:@" "];
}
textString = [textString stringByReplacingCharactersInRange:NSMakeRange(position, 0) withString:markedText];//替换回
NSLog(@"*******\n markedText:%@ \n position:%ld \n length:%ld \n ******",markedText,(long)position,(long)length);
if (markedText.length) {
[UIView performWithoutAnimation:^{
[self setMarkedText:textString selectedRange:NSMakeRange(position, markedText.length)];//不仅会设置标记区,也会设置选中区,这里textString为整个textField的text
[self setSelectedRange:NSMakeRange(position + markedText.length, 0)];
}];
} else {
[self setText:textString];
}
}
1
2
3
4
5
6
7
8
9
10
11
//标记区 - 标记区
- (NSRange)markedRang
{
UITextPosition * beginning = self.beginningOfDocument;
UITextRange * markedRang = self.markedTextRange;
UITextPosition * markedStart = markedRang.start;
UITextPosition * markedEnd = markedRang.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:markedStart];
const NSInteger length = [self offsetFromPosition:markedStart toPosition:markedEnd];
return NSMakeRange(location, length);
}
1
2
3
4
5
6
7
8
9
10
11
12
//选择区 - 复制的时候选中
- (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);
}
1
2
3
4
5
6
7
8
- (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];
}