I managed to get everything that works with a subclass of UITextField. You will probably want to move these delegate methods to the ViewController and set the special TextField delegate there. For the sake of this example, itβs easier to show you everything in one class. Obviously, you will have to configure the character sets that you are allowed to.
#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
source share