以相同的方式在GMSAutocomplete中使用textfield而不是searchbar

我正在使用谷歌地方自动完成API,我需要添加UITextField而不是具有相同function的UISearchBar。 这里是我从https://developers.google.com/places/ios-api/autocomplete获得的UISearchBar的工作代码。 我会自己添加textfield和tableview,如果有人只是帮助我从任何search关键字获取地址数组。 如从string(关键字)到数组(预测位置)。

import UIKit import GoogleMaps class ViewController: UIViewController { var resultsViewController: GMSAutocompleteResultsViewController? var searchController: UISearchController? var resultView: UITextView? override func viewDidLoad() { super.viewDidLoad() resultsViewController = GMSAutocompleteResultsViewController() resultsViewController?.delegate = self searchController = UISearchController(searchResultsController: resultsViewController) searchController?.searchResultsUpdater = resultsViewController let subView = UIView(frame: CGRectMake(0, 65.0, 350.0, 45.0)) subView.addSubview((searchController?.searchBar)!) self.view.addSubview(subView) searchController?.searchBar.sizeToFit() searchController?.hidesNavigationBarDuringPresentation = false self.definesPresentationContext = true } } extension ViewController: GMSAutocompleteResultsViewControllerDelegate { func resultsController(resultsController: GMSAutocompleteResultsViewController, didAutocompleteWithPlace place: GMSPlace) { searchController?.active = false print("Place name: ", place.name) print("Place address: ", place.formattedAddress!) } func resultsController(resultsController: GMSAutocompleteResultsViewController, didFailAutocompleteWithError error: NSError){ print("Error: ", error.description) } func didRequestAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func didUpdateAutocompletePredictionsForResultsController(resultsController: GMSAutocompleteResultsViewController) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } 

首先采取文本字段和表格视图。 然后钩住它。 整合您的GPA(Google Places API)并最终运行它。

 import UIKit import GooglePlaces class YourViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var PlaceTextField: UITextField! @IBOutlet weak var tableView: UITableView! var tableData=[String]() var fetcher: GMSAutocompleteFetcher? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.edgesForExtendedLayout = .None // Set bounds to inner-west Sydney Australia. let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366, longitude: 151.134002) let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725, longitude: 151.200349) let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner, coordinate: swBoundsCorner) // Set up the autocomplete filter. let filter = GMSAutocompleteFilter() filter.type = .Establishment // Create the fetcher. fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter) fetcher?.delegate = self PlaceTextField?.addTarget(self, action: "textFieldDidChange:",forControlEvents: .EditingChanged) tableView.delegate = self tableView.dataSource = self self.tableView.reloadData() } func textFieldDidChange(textField: UITextField) { fetcher?.sourceTextHasChanged(PlaceTextField.text!) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var section = indexPath.section var row = indexPath.row let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:"addCategoryCell") cell.selectionStyle = UITableViewCellSelectionStyle.None cell.backgroundColor = UIColor.clearColor() cell.contentView.backgroundColor = UIColor.clearColor() cell.textLabel?.textAlignment = NSTextAlignment.Left cell.textLabel?.textColor = UIColor.blackColor() cell.textLabel?.font = UIFont.systemFontOfSize(14.0) cell.textLabel?.text = tableData[indexPath.row] return cell } } extension YourViewController: GMSAutocompleteFetcherDelegate { func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) { tableData.removeAll() for prediction in predictions { tableData.append(prediction.attributedPrimaryText.string) //print("\n",prediction.attributedFullText.string) //print("\n",prediction.attributedPrimaryText.string) //print("\n********") } tableView.reloadData() } func didFailAutocompleteWithError(error: NSError) { //resultText?.text = error.localizedDescription print(error.localizedDescription) } } 

如果您使用UITextField和您自己的UITableView代替UISearchController,那么直接使用GMSAutocompleteTableDataSource类会更容易。

GoogleMaps Cocoapod的一个代码示例显示了如何执行此操作。 如果已安装该窗格,请在项目的Pods/GoogleMaps/GoogleMapsSDKDemos/SDKDemos/PlacesSamples目录中Pods/GoogleMaps/GoogleMapsSDKDemos/SDKDemos/PlacesSamples文件,或者运行pod try GoogleMaps下载示例。

对于印度的经度和纬度

//在你的View Controller中有TextField和TableView Setup

 import UIKit import GooglePlaces class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var txtField: UITextField! @IBOutlet weak var table1: UITableView! var tableData = [String]() var fetcher: GMSAutocompleteFetcher? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.edgesForExtendedLayout = [] let nsBoundsCorner = CLLocationCoordinate2D(latitude: 20.5937, longitude: 78.9629) let bounds = GMSCoordinateBounds(coordinate: nsBoundsCorner, coordinate: nsBoundsCorner) let filter = GMSAutocompleteFilter() filter.type = .establishment fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter) fetcher?.delegate = self txtField?.addTarget(self, action: #selector(textFieldDidChange(textField:)),for: .editingChanged) table1.delegate = self table1.dataSource = self self.table1.reloadData() // Do any additional setup after loading the view. } @objc func textFieldDidChange(textField: UITextField) { fetcher?.sourceTextHasChanged(txtField.text!) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var section = indexPath.section var row = indexPath.row let cell1 : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell1") cell1.selectionStyle = UITableViewCellSelectionStyle.none cell1.backgroundColor = UIColor.clear cell1.contentView.backgroundColor = UIColor.clear cell1.textLabel?.textAlignment = NSTextAlignment.left cell1.textLabel?.textColor = UIColor.black cell1.textLabel?.font = UIFont.systemFont(ofSize: 14.0) cell1.textLabel?.text = tableData[indexPath.row] return cell1 } // extension TableViewController: GMSAutocompleteFetcherDelegate { // // func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) { // // tableData.removeAll() // // for prediction in predictions { // // tableData.append(prediction.attributedPrimaryText.string) // // } // // table1.reloadData() // } // // } @IBAction func textField1(_ sender: Any) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension TableViewController: GMSAutocompleteFetcherDelegate { func didAutocomplete(with predictions: [GMSAutocompletePrediction]) { tableData.removeAll() for prediction in predictions{ tableData.append(prediction.attributedFullText.string) } table1.reloadData() } func didFailAutocompleteWithError(_ error: Error) { print(error.localizedDescription) } } 

//还要设置应用程序委托

 import UIKit import GooglePlaces import GoogleMaps @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //// [GMSPlacesClient provideAPIKey:...] // [GMSPlacesClient .provideAPIKey("xxxxxxxxxxxxxxxxxxxxxx")] GMSPlacesClient.provideAPIKey("xxxxxxx") GMSServices.provideAPIKey("xxxxxxxxxx") return true } } 

看到输出图像它的工作是这样的

由Govind库马尔12-12-2017