我通过将@Youngjin和@Exception对Swift 4和Google Places 2.6.0的回答结合起来,得到了一个可行的解决方案。
要访问GMSAutocompleteViewController搜索栏:
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") // This performs the automatic searching.
我发现当我试图在didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController)中设置文本时,会收到EXC_BAD_ACCESS错误。
所以我改为将这段代码放入展示自动完成功能的完成块中,这样就可以正常运行了。
将所有内容组合在一起:
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")
}
编辑:我发现这个解决方案似乎只适用于iOS 11。
let searchBar = subOfContentView [0] as!UISearchBar
在iOS 10及可能更低版本上会失败。