iOS之UITextField对输入的内容的长度限制和内容限制

这里讲解两个对文本框输入内容的长度的限制:

首先是通过添加事件的方式来限制:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建文本框
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 50)];
    //文本框的边框的样式
    textField.borderStyle = UITextBorderStyleRoundedRect;
    //为文本框添加事件(因为UITextField是继承于UIControl的)
    [textField addTarget:self action:@selector(limit:) forControlEvents:UIControlEventEditingChanged];
    //添加到当前视图
    [self.view addSubview:textField];
}

//限制文本框的输入内容和文本的长度
- (void)limit:(UITextField *)textField{
    
    //限制文本的输入长度不得大于10个字符长度
    if (textField.text.length >= 10){
    
        //截取文本字符长度为10的内容
        textField.text = [textField.text substringToIndex:10];
    }
}

其次是通过UITextField的代理方法来进行限制的,并在此方法中进行输入内容的限制:

//设置只允许输入123和qwe(区分大小写)
#define textFieldContent @"123qwe"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建文本框
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 50)];
    //文本框的边框的样式
    textField.borderStyle = UITextBorderStyleRoundedRect;
    //设置当前控制器为文本框的代理
    textField.delegate = self;
    //添加到当前视图
    [self.view addSubview:textField];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //先设置只能输入的集合  invertedSet就是将咱们允许输入的字符串的字符找出
    NSCharacterSet *canInputSet = [[NSCharacterSet characterSetWithCharactersInString:textFieldContent] invertedSet];
    //把允许输入的内容转化成数组,再转化成字符串
    NSString *str = [[string componentsSeparatedByCharactersInSet:canInputSet] componentsJoinedByString:@""];
    //判断输入的字符是否包含在允许输入的字符之内
    BOOL isSuccess = [string isEqualToString:str];
    //限制文本框输入内容的长度不得超过10且有输入内容的限制
    if (textField.text.length <= 10 && isSuccess){
        //返回值为YES的时候,文本框可以进行编辑
        return YES;
    }else{
        //当返回NO的时候,文本框内的内容不会在再改变,甚至不能进行删除
        return NO;
    }
}





你可能感兴趣的:(iOS开发之UI控件常见问题)