限制UIAlertViewStylePlainTextInput的字符数

时间:2014-05-14 11:21:57

标签: ios uialertview

我正在使用以下方法创建文本输入uialertview。

[dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];

如何限制用户可以输入的字符数?

2 个答案:

答案 0 :(得分:3)

试试此代码

首先添加UITextFieldDelegate

UIAlertView *dialog = [[UIAlertView alloc]init];// Setup your alert 
[dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
[dialog textFieldAtIndex:0].placeholder = @"";//add this if you need
[dialog textFieldAtIndex:0].delegate = self;

并根据Check this Answer

添加文本字段委托
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 25) ? NO : YES;
}

也许它会帮助你。

答案 1 :(得分:0)

如果您有alertView实例,请执行以下操作

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([self.alertView textFieldAtIndex:0])
    {
      NSUInteger newLength = [textField.text length] + [string length] - range.length;
      return (newLength > 25) ? NO : YES;
    }
    return YES; // suppress warning about control reaching end of non-void function
}