在调试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)]; [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 { 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]; }
|