我正在寻找一种方法来实现UITextField的输入掩码,如下所示:
主要特点:
答案 0 :(得分:0)
我能够使用UITextField子类获得所有这些功能。您可能希望将这些委托方法移动到ViewController中并在那里设置自定义TextField委托。为了这个例子,更容易向你展示一个类中的所有内容。显然,您将不得不调整那些满足您需求的字符集。
#import "TextField.h"
@interface TextField()<UITextFieldDelegate>
@end
@implementation TextField
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
}
return self;
}
- (UITextPosition *)closestPositionToPoint:(CGPoint)point{
UITextPosition *beginning = self.beginningOfDocument;
UITextPosition *end = [self positionFromPosition:beginning offset:self.text.length];
return end;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(paste:)
|| action == @selector(select:)
|| action == @selector(selectAll:)
|| action == @selector(cut:)){
return NO;
}
return [super canPerformAction:action withSender:sender];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location == 0 && [string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location == NSNotFound) {
return NO;
}else if (range.location == 1 && [string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == NSNotFound){
return NO;
}
return YES;
}
@end