在uialertview中添加了对textfield的iphone验证

duk*_*duk 5 iphone objective-c ios4 ios

我使用UIAlertViewStylePlainTextInput在UIAlertView中添加了UITextField.我需要验证alertview中存在的文本字段,即它不应该为空

我应该怎么做?

ren*_*ene 11

让我们假设你有一个"OK"按钮(或类似的东西),就像UIAlertView的其他第一个按钮一样.进一步假设您希望当且仅当文本字段中的文本长度大于0时才启用该按钮.然后验证的解决方案很简单.在UIAlertView实现的委托中:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    return [[alertView textFieldAtIndex:0].text length] > 0;
}
Run Code Online (Sandbox Code Playgroud)

这比其他一些答案(使用clickedButtonAtIndex :)具有优势,即用户可以立即知道文本字段是否包含有效输入.

Apple的文档中没有很好地解释这个委托消息,但它的效果非常好.对文本字段值的任何更改都将导致发送此消息,并相应地启用或禁用"确定"按钮.


Ali*_*i3n 0

您可以从 UIAlertViewDelegate 方法调用您的验证方法

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
Run Code Online (Sandbox Code Playgroud)