使用 AlertView 文本输入

Using AlertView Text Input

如何使用从 AlertView 输入的文本?在此示例中,我使用 AlertView 输入一个 phone 数字,然后将其存储在 textfield.text 中(下面的代码)。我想在同一 .m 文件中包含的另一种方法中使用此数据。如何从另一个方法中正确引用此输入(phone 数字)数据?

- (void) alertView: (UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Capture the phone number input from the alert pop-up window. UIAlertView Delegate added to allow the OS trigger this method to read the data.

    if (alertView.tag == 12) {
        if (buttonIndex == 1) {
            UITextField *textfield = [alertView textFieldAtIndex:0];
            NSLog(@"phonenumber: %@", textfield.text);

        }

    }

}

您可能需要做以下两件事之一。第一个选项是在 class:

中为您的 phone 号码设置一个 ivar 或 属性
@implementation SomeViewController {
    NSString* _phoneNumber;
}

- (void) alertView: (UIAlertView *)alertView clickedButtonAtIndex (NSInteger)buttonIndex
{
    // Capture the phone number input from the alert pop-up window. UIAlertView Delegate added to allow the OS trigger this method to read the data.

    if (alertView.tag == 12) {
        if (buttonIndex == 1) {
            UITextField *textfield = [alertView textFieldAtIndex:0];
            _phoneNumber = textField.text;
        }
    }
}

- (void)someOtherMethod {
    NSLog(@"phonenumber: %@", _phoneNumber);
}
@end

或者,您可以让您的其他方法将 phone 数字文本作为参数:

- (void) alertView: (UIAlertView *)alertView clickedButtonAtIndex (NSInteger)buttonIndex
{
    // Capture the phone number input from the alert pop-up window. UIAlertView Delegate added to allow the OS trigger this method to read the data.

    if (alertView.tag == 12) {
        if (buttonIndex == 1) {
            UITextField *textfield = [alertView textFieldAtIndex:0];
            [self someOtherMethodThatHandlesAPhoneNumber:textField.text];
        }
    }
}

- (void)someOtherMethodThatHandlesAPhoneNumber:(NSString*)phoneNumber {
    NSLog(@"phonenumber: %@", phoneNumber);
}