让UITextFeld输入的时候和输入银行卡一样的格式

#import "ViewController.h"

#define NUMBERS @"0123456789"


@interface ViewController () <UITextFieldDelegate> {

    UITextField * _numberFielde;

    UILabel *_numLabel;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    

    [super viewDidLoad];

    

    _numberFielde = [[UITextField alloc] initWithFrame:CGRectMake(0, 100,self.view.frame.size.width, 50)];

    _numberFielde.layer.borderColor = [UIColor grayColor].CGColor;

    _numberFielde.layer.borderWidth = 1.0f;

    _numberFielde.delegate = self;

    _numberFielde.placeholder = @"请输入数字";

    [_numberFielde becomeFirstResponder];

    

    [self.view addSubview:_numberFielde];

    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

    button.frame = CGRectMake(100, 200, 100, 30);

    [button addTarget:self action:@selector(getNum) forControlEvents:UIControlEventTouchUpInside];

    [button setTitle:@"取得数字" forState:UIControlStateNormal];

    

    [self.view addSubview:button];

    

    _numLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 250, self.view.frame.size.width, 50)];

    _numLabel.textAlignment = NSTextAlignmentCenter;

    

    [self.view addSubview:_numLabel];

}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];

    

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    

    BOOL basicTest = [string isEqualToString:filtered];

    

    if (basicTest) {

        if (textField == _numberFielde) {

            

            // 四位加一个空格

            if ([string isEqualToString:@""]) { // 删除字符

                

                if ((textField.text.length - 2) % 5 == 0) {

                    textField.text = [textField.text substringToIndex:textField.text.length - 1];

                }

                return YES;

            } else {

                if (textField.text.length % 5 == 0) {

                    textField.text = [NSString stringWithFormat:@"%@ ", textField.text];

                }

            }

            return YES;

        }

    } else {

        return NO;

    }

    

    return YES;

}


- (void)getNum {

    _numLabel.text = [self deleteSpace];

}



- (NSString *)deleteSpace {

    NSString *username = _numberFielde.text;

    username =  [username stringByReplacingOccurrencesOfString:@" " withString:@""];

    return username;

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}


@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值