如何在UIAlertView中初始化文本字段

29

更新后的 UIAlertView 现在具有一种样式,允许在 UIAlertView 中使用文本输入字段。

alert.alertViewStyle = UIAlertViewStylePlainTextInput;

这个方法很好,但我想把输入文本初始化为默认文本,比如 "sample"。

我看到有些人过去使用了不被记录的API(这个也很好用)

[alert addTextFieldWithValue:@"sample text" label:@"Text Field"];

但由于这仍不是官方的 Apple 公共 API,我无法使用它。

还有其他方法来处理这个问题吗?我尝试在 willPresentAlertView 中初始化,但是似乎文本字段是只读的。

谢谢。

5个回答

57
UIALertView有一个textFieldAtIndex:方法,可以返回您想要的UITextField对象。

对于UIAlertViewStylePlainTextInput,文本字段的索引为0。

然后,您可以设置文本字段的占位符(或文本)属性:

UIAlertView *alert = ....
UITextField *textField = [alert textFieldAtIndex:0];
textField.placeholder = @"your text";

UIAlertView类参考文档


这似乎不再起作用了。 textFieldAtIndex 产生了以下错误:*** 未捕获的异常 'NSInvalidArgumentException',原因是:'textFieldIndex(0)超出文本字段数组的范围'。 - Symmetric
对我有用,但是为什么!!! 效果如何反映到警报上!! 无法理解! - OXXY
1
@Symmetric,请确保在尝试获取UITextField之前设置[alertView setAlertViewStyle:UIAlertViewStylePlainTextInput]; - bubastis

9

简单易行的方法

 UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"your title" message:@"your message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    alerView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [[alerView textFieldAtIndex:0] setPlaceholder:@"placeholder text..."];
    [alerView show];

8

虽未测试,但我认为这个应该能够起作用:

UIAlertView* alert = [[UIAlertView alloc] initWithTitle:...];
UITextField* textField = [alert textFieldAtIndex:0];
textField.text = @"sample";
[alert show];

6

要在 uiAlertView 中设置默认值,可以使用以下方法。

UIAlertView *alert = ....
UITextField *textField = [alert textFieldAtIndex:0];
[textField setText:@"My default text"];
[alert show];

0
- (IBAction)showMessage:(id)sender {
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Add New Category"
                                                      message:nil
                                                     delegate:self 
                                            cancelButtonTitle:@"Add"
                                            otherButtonTitles:@"Cancel", nil];
    [message setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [message show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Add"])
    {
        UITextField *username = [alertView textFieldAtIndex:0];
        NSLog(@"Category Name: %@", username.text);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接