Embed an input mask in a UITextField

I am looking for a way to implement an input mask for a UITextField as follows: enter image description here

Key features:

  • Show placeholder for empty char to the right of cursor
  • Prevent the entry of invalid characters for the current cursor position (for example, the first char can only be a Latin char, the second char can only be a number)
  • Prohibit selection, cut and paste
  • Disable cursor position adjustment (user can only add a new char or delete the last one)
+5
source share
1 answer

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 
0
source

All Articles