如何限制UIAlert iOS中文本字段的文本长度。

时间:2014-03-22 21:04:24

标签: ios objective-c uitextfield uialertview

如何使用现有代码限制可以在UIAlertView的文本字段中输入的文本数量?

我是iOS应用开发的新手。

我的代码如下:

if(indexPath.row== 1){
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:@"Enter Novena Day"
                              message:@"Please enter the day of Novena:"
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              otherButtonTitles:@"Ok", nil];
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *textField = [alertView textFieldAtIndex:0];
    textField.keyboardType = UIKeyboardTypeNumberPad;

    [alertView show];

}

3 个答案:

答案 0 :(得分:2)

初始化警报视图时:

[[alertView textFieldAtIndex:0] setDelegate:self];

现在,self这里是您的视图控制器。因此,您需要在其声明中添加<UITextFieldDelegate>

现在实现委托方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > self.maxAlertTextFieldLength) ? NO : YES;
}

这取自评论中的this answer链接答案。

答案 1 :(得分:0)

我建议更好地使用通知

检查这个

UITextField *textField = [alertView textFieldAtIndex:0];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldMaxLimit:) name:UITextFieldTextDidChangeNotification object:textField];


-(void)textFieldMaxLimit:(NSNotification*)notification
{
  UITextField *textField=(UITextField*)notification.object;

        if ([[textField text] length]>22) //choose your limit for characters
        {
            NSString *lastString=[[textField text] substringToIndex:[[textField text] length] - 1];;
            [textField setText:lastString];
        }
 } 

答案 2 :(得分:0)

实施shouldChangeCharactersInRange委托,检查您的情况并返回所需的值。

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

  BOOL isValid = YES;

  @try
  {
     if(5 < [textField.text length])
     {
        isValid = NO;
     }
  }
  @catch (NSException *exception)
  {
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
  }
  @finally
  {
     return isValid;
  }
}