欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UITextView和UITextField限制输入长度

程序员文章站 2022-04-06 08:08:36
...

UITextView要实现UITextViewDelegate协议:

 _descriptionTextView.delegate=self;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@""] && range.length > 0) {
    // 删除字符肯定是安全的
    return YES;
    }
    if (textView.text.length - range.length + text.length > 1000) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
    return NO;
    }
    return YES;
}

UITextField要实现UITextFieldDelegate协议:

 _exchangeTextField.delegate=self;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.exchangeTextField && textField.isFirstResponder) {
        NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
           if ([toBeString length] > 8) {
               textField.text = [toBeString substringToIndex:8];
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
               [alert show];
               return NO;
           }
           return YES;
    }
     return YES;
   
}
相关标签: IOS ios