平时项目中,我们可能会遇到区分用户输入和粘贴的情况.例如当用户粘贴时,清空textField原有的内容.本文通过创建一个UITextField的子类来实现次功能.
子类代码
头文件
@protocol YJTextFieldDelegate <UITextFieldDelegate>
/**
* 给textField粘贴时,不再调用- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string方法
* 会调用此方法
*/
- (BOOL)textField:(YJTextField *)textField shouldPasteCharactersInRange:(NSRange)range replacementString:(NSString *)string;
@end
@interface YJTextField : UITextField
@property (nonatomic, weak) id<YJTextFieldDelegate, UITextFieldDelegate> delegate;
@end
实现文件
#import "YJTextField.h"
@implementation YJTextField
- (void)paste:(id)sender {
UITextPosition *begin = self.beginningOfDocument;
UITextPosition *start = self.selectedTextRange.start;
UITextPosition *end = self.selectedTextRange.end;
NSRange range = NSMakeRange([self offsetFromPosition:begin toPosition:start], [self offsetFromPosition:start toPosition:end]);
if ([self.delegate respondsToSelector:@selector(textField:shouldPasteCharactersInRange:replacementString:)] &&
[self.delegate textField:self shouldPasteCharactersInRange:range replacementString:[UIPasteboard generalPasteboard].string]) {
[self replaceRange:self.selectedTextRange withText:[UIPasteboard generalPasteboard].string];
}
}
@end
在需要识别粘贴的地方,用YJTextField,实现- (BOOL)textField:(YJTextField *)textField shouldPasteCharactersInRange:(NSRange)range replacementString:(NSString *)string;
代理方法即可.
网友评论