0
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"......" message:@"......" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"OK", nil];

[alert show];

我正在显示警报视图以使用警报视图的文本字段添加新类别,当用户点击警报的确定按钮时,我首先检查用户是否输入了任何内容,如果没有,则显示另一个警报,其中包含一些消息让用户知道文本字段是强制性的,但之前添加新类别的警报消失了。

我希望该警报留在屏幕上。所以我该怎么做 ??

这是崩溃报告和代码::

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Vehicle Category" message:@"this gets covered!" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"OK", nil];
            alert.tag = 5;

txtAddVehicleCategory = [[UITextField alloc]initWithFrame:CGRectMake(12, 45, 260, 25)];

[txtAddVehicleCategory setBackgroundColor:[UIColor whiteColor]];

txtAddVehicleCategory.placeholder = @"Enter Vehicle Category";

txtAddVehicleCategory.contentVerticalAlignment =       UIControlContentVerticalAlignmentCenter;

[alert addSubview:txtAddVehicleCategory];


CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, -50);

[alert setTransform:myTransform];

[alert show];

'NSInvalidArgumentException',原因:'textFieldIndex (0) 超出了文本字段数组的范围'

4

1 回答 1

2

当您想实现一些在 中输入文本的规则时UIAlertView,您应该禁用OK警报视图的按钮,直到用户遵守规则。UIAlertViewDelegate您可以使用方法来实现这一点。调查alertViewShouldEnableFirstOtherButton:

NO从方法返回,直到遵循规则

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    // When return NO, OK button is disabled.
    // When return YES, rule is followed and OK button gets enabled.
    return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
}

编辑

我提供的代码假设您使用的是默认警报视图样式文本字段,因此会崩溃。

您不应该这样addSubviewUIAlertView,因为警报视图的视图层次结构是私有的。最新的iOS7 不会显示用户添加的任何子视图UIAlertView。所以我建议你不要这样做。

来自Apple 文档

UIAlertView 类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不得修改。

相反,使用UIAlertViewStyle.

以下是支持的样式,

typedef enum {
   UIAlertViewStyleDefault = 0,
   UIAlertViewStyleSecureTextInput,
   UIAlertViewStylePlainTextInput,
   UIAlertViewStyleLoginAndPasswordInput
} UIAlertViewStyle;

使用适合您要求的那一款。要验证用户输入的输入,请使用我建议的上述方法。请参阅这个简单的指南/教程,以使用这些样式的警报视图。

希望有帮助!

于 2013-10-07T07:46:30.000 回答