两个文本字段显示相同的GMSPlace自动完成

时间:2019-05-30 10:46:07

标签: ios swift google-maps autocomplete uitextfield

在我的GMSAUtocompleteController中,我有两个文本字段,但单击时它们显示相同的位置

extension RideAddDetailsViewController: GMSAutocompleteViewControllerDelegate {
    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {


    locationTextField.text = place.name
    destinationTextField.text = place.name


    dismiss(animated: true, completion: nil)
  }
   func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
    // Handle the error
    print("Error: ", error.localizedDescription)
 }
 func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    // Dismiss when the user canceled the action
    dismiss(animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:0)

您可以使用标签将它们分开。

    if textField.isEqual(locationTextField)
    {

       let autocompleteController = GMSAutocompleteViewController()
       autocompleteController.view.tag = 1 // assign the tag you want
       autocompleteController.delegate = self

       present(autocompleteController, animated: true, completion: nil)
    }
    else if  textField.isEqual(destinationTextField)
   {

       let autocompleteController = GMSAutocompleteViewController()
       autocompleteController.view.tag = 2 // assign the tag you want
       autocompleteController.delegate = self

       present(autocompleteController, animated: true, completion: nil)
    }

现在,您可以像这样将值与委托方法分开,并分配给文本字段。

    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {

    if viewController.view.tag == 1
    {
       locationTextField.text = place.name
     }
     else viewController.view.tag == 2
     {
        destinationTextField.text = place.name
     }


        dismiss(animated: true, completion: nil)
  }

答案 1 :(得分:0)

我在两个IBAction中都将单击的textField的引用设置为selectedTextField。

 var selectedTextField = UITextField()

 @IBAction func locationTextFieldTapped(_ sender: Any) {
    selectedTextField = locationTextField
    //locationTextField.resignFirstResponder()
    let autoCompleteController = GMSAutocompleteViewController()
    locationTextField.tag = 0
    autoCompleteController.delegate = self
    present(autoCompleteController, animated: true, completion: nil)
}

@IBAction func destinationTextField(_ sender: Any) {
    selectedTextField = destinationTextField
    //destinationTextField.resignFirstResponder()
    let autoCompleteController = GMSAutocompleteViewController()
    destinationTextField.tag = 1
    autoCompleteController.delegate = self
    present(autoCompleteController, animated: true, completion: nil)

    }

Then in the GMSAutocompleteViewControllerDelegate

I did this:
     self.selectedTextField.text = place.name