如何在两个文本字段中使用自动完成功能?

时间:2016-07-16 13:46:16

标签: ios objective-c autocomplete uitextfield google-places

在我的应用中,我有两个textFields,点击每个textField我可以选择从谷歌地方加载的地方自动完成。在用户处理程序中我必须分配我必须显示的文本字段结果。如果我点击第一个文本字段,显示第二个文本字段的值反之亦然。我为两个文本字段设置标记值。以下是我的完整代码。谢谢。

//when first textfield clicked
- (IBAction)onLaunchClicked:(id)sender {
        GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
        acController.delegate = self;
        [self presentViewController:acController animated:YES completion:nil];

    }

//when second textfield clicked
- (IBAction)to_click:(id)sender {
        GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
        acController.delegate = self;
        [self presentViewController:acController animated:YES completion:nil];
    }


// Handle the user's selection.
    - (void)viewController:(GMSAutocompleteViewController *)viewController
    didAutocompleteWithPlace:(GMSPlace *)place {
        [self dismissViewControllerAnimated:YES completion:nil];
        // Do something with the selected place.
        NSLog(@"Place name %@", place.name);
        NSLog(@"Place address %@", place.formattedAddress);
        NSLog(@"Place attributions %@", place.attributions.string);

 //have to set values in correct textfields
    if (textfield.tag == 10001){
    from_txt.text=place.formattedAddress;
   }
    else {
    to_txt.text= place.formattedAddress;
        }

}

1 个答案:

答案 0 :(得分:0)

您需要在textField中再声明一个viewController个实例

UITextField *selTextField;

现在将点击的textField的引用设置为两个IBAction中的selTextField

- (IBAction)onLaunchClicked:(id)sender {
    self.selTextField = (UITextField*) sender;
    GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
    acController.delegate = self;
    [self presentViewController:acController animated:YES completion:nil];
}

- (IBAction)to_click:(id)sender {
    self.selTextField = (UITextField*) sender;
    GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
    acController.delegate = self;
    [self presentViewController:acController animated:YES completion:nil];
}

现在使用GMSAutocompleteViewController

的委托方法
- (void)viewController:(GMSAutocompleteViewController *)viewController
didAutocompleteWithPlace:(GMSPlace *)place {
    [self dismissViewControllerAnimated:YES completion:nil];
    // Do something with the selected place.
    NSLog(@"Place name %@", place.name);
    NSLog(@"Place address %@", place.formattedAddress);
    NSLog(@"Place attributions %@", place.attributions.string);

    //Set textField value
    self.selTextField.text=place.formattedAddress;
}