我使用UIAlertViewStylePlainTextInput在UIAlertView中添加了UITextField。我需要验证alertview中存在的文本字段,即它不应该是空的
我该怎么办?
答案 0 :(得分:11)
让我们假设你有一个“OK”按钮(或类似的东西),就像UIAlertView的其他第一个按钮一样。进一步假设您希望当且仅当文本字段中的文本长度大于0时才启用该按钮。然后验证的解决方案很简单。在UIAlertView实现的委托中:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
return [[alertView textFieldAtIndex:0].text length] > 0;
}
这比其他一些答案(使用clickedButtonAtIndex :)具有优势,即用户可以立即知道文本字段是否包含有效输入。
Apple委员会的文档中没有很好地解释这个委托消息,但它的效果非常好。对文本字段值的任何更改都将导致发送此消息,并相应地启用或禁用“确定”按钮。
答案 1 :(得分:0)
您可以从UIAlertViewDelegate方法
调用您的validate方法- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
答案 2 :(得分:0)
将文本字段事件“Editing Did End”或类似内容绑定到文件所有者中用于处理验证的方法。该方法是您在controller.m文件中编写的方法,并在controller.h文件中声明。控制器文件的确切名称取决于应用程序代码库的结构。
如何处理验证失败的情况,例如内容为空,取决于您的应用程序的需求。例如,如果内容为空,则需要提醒用户,然后将焦点重置为文本字段。
如果您对iOS编程有点新手,您可能会发现Ray Wnderlich的教程很有用。 http://www.raywenderlich.com/
我发现“iOS Apprentice”做得很好。另外,Dave Mark的新书“开始iOS 5开发”可能很有用。
答案 3 :(得分:0)
将alertView的委托设置为当前的viewController
然后在委托方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)return; //for cancel button
UITextField *textField = [alertView textFieldAtIndex:0]; // since there is only one UITextField in alertView
if ([textField.text length] > 0) // checking the length of the text in UITextField
{
// Your code goes here
}
}
我希望这会有所帮助 BR,Hari
答案 4 :(得分:0)
1:在alertView中获取UITextField
:
self.alertViewTextField = [alertView textFieldAtIndex:0];
2:检查textField编辑更改时的文本长度:
[self.alertViewTextField addTarget:self action:@selector(alertViewTextFieldDidChanged) forControlEvents:UIControlEventEditingChanged];
-(void)alertViewTextFieldDidChanged{
if(self.alertViewTextField.text.length == 0){
// ...
}
}