2012-03-08 68 views
29

更新UIAlertView现在有一个风格,它允许在UIAlertView我怎么能初始化一个UIAlertView中的文本字段

alert.alertViewStyle = UIAlertViewStylePlainTextInput; 

这种运作良好,文本输入框,但我想初始化一个defualt输入文本像“样本”这样的文字。

我看到,在过去的人都喜欢使用未公开的API(这伟大工程)

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

但由于这是还没有一个官方的苹果公共API我不能使用它。

任何其他方式来处理?我尝试在willPresentAlertView中初始化,但文本字段似乎是只读的。

感谢

回答

8

没有测试,但我认为这会工作:

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

UIALertView有一个textFieldAtIndex:方法,返回你想要的UITextField对象。

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

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

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

UIAlertView Class Reference

+0

大 - 谢谢你,工作 – timeview 2012-03-08 19:06:00

+1

不客气:)如果回答了你的问题,你可以通过点击旁边的蜱接受答案到它 – Mutix 2012-03-08 20:07:21

+0

这似乎没有工作了。 textFieldAtIndex产生这个错误:***终止应用程序,由于未捕获异常'NSInvalidArgumentException',原因:'textFieldIndex(0)在文本字段数组边界之外'。 – Symmetric 2013-11-06 19:38:15

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); 
    } 
} 
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]; 
+0

完美答案:) – 2015-11-03 07:02:32