写好以后才发现
// 这个就 直接实现了下面的功能.... deleteBackward
项目中要自定义键盘, 所以自己写一个删除的按钮的点击事件, 写完以后才知道, 苹果爸爸给出了一个API:deleteBackward
删除按钮的点击事件
NSRange tmpRange = searchInput.selectedRange;
if(tmpRange.location==0)return;
NSRangerange =NSMakeRange(tmpRange.location-1,1);
NSLog(@"tmpRange --- %lu",(unsignedlong)tmpRange.location);
NSMutableString* mutableString = [[NSMutableString alloc] initWithFormat:@"%@",searchInput.text];
[mutableStringreplaceCharactersInRange:range withString:@""];
NSLog(@"mutableString --- %@",mutableString);
searchInput.text= mutableString;
[searchInput setSelectedRange:NSMakeRange(tmpRange.location - 1, 0)];
类别:
//
// UITextField+Selection.h
// redarrow
//
// Created by lvzhao on 2018/6/24.
// Copyright © 2018年 GP. All rights reserved.
//
#import
@interfaceUITextField (Selection)
- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;
@end
//
// UITextField+Selection.m
// redarrow
//
// Created by lvzhao on 2018/6/24.
// Copyright © 2018年 GP. All rights reserved.
//
#import "UITextField+Selection.h"
@implementationUITextField (Selection)
- (NSRange) selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
constNSIntegerlocation = [selfoffsetFromPosition:beginningtoPosition:selectionStart];
constNSIntegerlength = [selfoffsetFromPosition:selectionStarttoPosition:selectionEnd];
returnNSMakeRange(location, length);
}
- (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 = [selftextRangeFromPosition:startPositiontoPosition:endPosition];
[selfsetSelectedTextRange:selectionRange];
}
@end