I need help to set text in searchBar of GMSAutocompleteViewController
when open in my App. I am using GMSAutocompleteViewController
in Google Place AutocompleteViewController.
I got a working solution by combining @Youngjin and @Exception's answers for Swift 4 and Google Places 2.6.0
To access the GMSAutocompleteViewController searchbar:
let views = gmsAutoCompleteViewController.view.subviews
let subviewsOfSubview = views.first!.subviews
let subOfNavTransitionView = subviewsOfSubview[1].subviews
let subOfContentView = subOfNavTransitionView[2].subviews
let searchBar = subOfContentView[0] as! UISearchBar
Then to set the text and also search automatically:
searchBar.text = "Your address"
searchBar.delegate?.searchBar?(searchBar, textDidChange: "Your address") // This performs the automatic searching.
I found that I received a EXC_BAD_ACCESS error when attempting to set the text from within didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController).
So I instead put this code in the completion block where I present the autoCompleteController, which works without issue.
Combining it all together:
let gmsAutoCompleteViewController = GMSAutocompleteViewController()
gmsAutoCompleteViewController.delegate = self
present(gmsAutoCompleteViewController, animated: true) {
let views = gmsAutoCompleteViewController.view.subviews
let subviewsOfSubview = views.first!.subviews
let subOfNavTransitionView = subviewsOfSubview[1].subviews
let subOfContentView = subOfNavTransitionView[2].subviews
let searchBar = subOfContentView[0] as! UISearchBar
searchBar.text = "Your address"
searchBar.delegate?.searchBar?(searchBar, textDidChange: "Your address")
}
EDIT: I found that this solution only seems to work on iOS 11.
let searchBar = subOfContentView[0] as! UISearchBar
will fail on iOS 10, and possibly lower versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With