关于C#:如何在UIAlert iOS中限制文本字段的文本长度。

How to limit text length for a textfield in a UIAlert iOS.

本问题已经有最佳答案,请猛点这里访问。

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

我是iOS应用开发的新手。

我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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];

}


初始化警报视图时:

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

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

现在实现委托方法:

1
2
3
4
5
- (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;
}

这是从此答案中的链接答案中获取的。


实现shouldChangeCharactersInRange委托,检查条件并返回所需的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (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
 exception: Name- %@ Reason->%@"
, __PRETTY_FUNCTION__,[exception name],[exception reason]);
  }
  @finally
  {
     return isValid;
  }
}


我建议更好地使用通知

检查这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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];
        }
 }