IOS 9 - 如何在UIAlertController中获取textField的值?

时间:2016-06-02 19:13:57

标签: ios objective-c uialertcontroller

我试图从UIAlertController获取textField值,但每当我尝试输入值(Name)并将其显示在标签时,输出都不会显示任何内容。

- (IBAction)button:(id)sender {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Test" message:@"Please Enter your name " preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Person Name ";
        textField.textColor = [UIColor blueColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.secureTextEntry = NO;

    }];
    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"ENTER, please"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action)
                                {
                                    //Handle the ENTER button 
                                   // how to Display the name in the label

                                }];
    UIAlertAction* noButton = [UIAlertAction
                               actionWithTitle:@"No, thanks"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action)
                               {
                                   //Handle no button. 
                               }];


    [alert addAction:yesButton];
    [alert addAction:noButton];

    [self presentViewController:alert animated:YES completion:nil];

}

1 个答案:

答案 0 :(得分:1)

我从旧项目中撤出的快速示例

     alert.addAction(UIAlertAction(title: "Send", style:   UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
        if let textFields = alert.textFields {
            if let textField = textFields.first {

            }
        }
    }))

在您的应用程序中,它会像这样:

UIAlertAction* yesButton = [UIAlertAction actionWithTitle:@"ENTER, please"   style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
    NSArray *textFields = alert.textFields;
    // Probably smart to do some nil checking here
    NSLogv(@"%@", textFields.first.text);
    // add to label like so
    label.text = textFields.first.text;
}];