GMSAutocompleteViewController

GMSAutocompleteViewController

在我的应用程序中打开时,我需要帮助来设置GMSAutocompleteViewController的searchBar中的文本。我在Google Place AutocompleteViewController中使用GMSAutocompleteViewController

swift - 如何在Google Place AutocompleteViewController中的GMSAutocompleteViewController中设置文本-LMLPHP

最佳答案

通过结合@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.

我发现尝试从内部设置文本时收到EXC_BAD_ACCESS错误
didRequestAutocompletePredictions(_ viewController:GMSAutocompleteViewController)。

因此,我将这段代码放在完成模块中,其中显示了autoCompleteController,该模块可以正常工作。

结合在一起:
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以及更低版本上失败。

09-04 18:05