5

I am looking for a method to implement an input mask to UITextField like this: enter image description here

Key features:

  1. Show placeholder for an empty char to the right of the cursor
  2. Prohibit the input of incorrect chars for current cursor position (for example, first char can only be a latin char, second char can only be a number)
  3. Prohibit select, cut and paste
  4. Prohibit setting the cursor position (the user will only be able to add a new char or delete the last)
nyuen
  • 8,829
  • 2
  • 21
  • 28
Citrael
  • 542
  • 4
  • 17
  • that might be useful for couple of your points:http://stackoverflow.com/questions/2388448/re-apply-currency-formatting-to-a-uitextfield-on-a-change-event/2919532#2919532 – casillas Apr 21 '15 at 18:46

1 Answers1

0

I was able to get all of that working with a UITextField subclass. You're probably going to want to move those delegate methods into a ViewController and set the custom TextField delegate there. For the sake of this example it's easier to show you everything in one class. Obviously you're going to have to tweak those character sets allowed to meet you needs.

#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
Dare
  • 2,497
  • 1
  • 12
  • 20