I am working on a form app on iOS 11 using Swift 4. I'd like to put the return of Google's selector (PlaceAutocomplete) in the UITextField of one of the cells of my UITableView. The issue is that despite assigning new values, the text fields remain blank. After debugging for a while it seems that something is discarding the content of my UITextField when the location is being selected.
These are the GooglePlaceAutocomplete callbacks with the result value assignment :
extension MyUITableViewController, GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
let indexPath4 = IndexPath(row: 4, section: 0)
let cell4 = tableView.cellForRow(at: indexPath4) as! InputPlacePicker
cell4.inputTextField.text = place.name
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error: ", error.localizedDescription)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
}
And this is the call to GooglePlaceAutocomplete
@objc func pickPlace() {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
present(autocompleteController, animated: true, completion: nil)
}
Changing the cells directly is probably not a good idea, since everytime the UITableView
is reloaded, cells get recycled and depending on your tableView(_:cellForRowAt:)
implementation, your UITextField
might get overwritten or end up somewhere else.
It is a better practice to have some kind of model or state in your view controller, which holds the state for each cell in the different sections.
Change this state (for instance a list of place names) in your GooglePlacesAutocomplete delegate and call reloadData
on your tableView
to get the new data from the changed state.
In your tableView(_:cellForRowAt:)
implementation, you set inputTextField.text = place.name
before you return it, this way all cells should end up with the right place name from your internal state.