如何实现自动完成表视图google maps swift?

时间:2021-10-24 14:32:09

I am trying to implement google maps autocomplete for cities. When they type in the text field, the table view should auto populate with potential cities based on the user's input. For now, I want to print the results in the log, but I am not sure if I am doing this correctly. This is the kind of results that appears in my log Result Austin{ GMSAutocompleteMatch = "<GMSAutocompleteMatchFragment: 0x608000235e60>"; }

我正在尝试为城市实施谷歌地图自动完成功能。当他们在文本字段中键入时,表视图应根据用户的输入自动填充潜在的城市。现在,我想在日志中打印结果,但我不确定我是否正确执行此操作。这是我的日志结果Austin中出现的那种结果{GMSAutocompleteMatch =“ ”; } :0x608000235e60>

var placesClient: GMSPlacesClient!

override func viewDidLoad() {
    super.viewDidLoad()

    placesClient = GMSPlacesClient.shared()

}



func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        placeAutoComplete()
        return true
    }

    func placeAutoComplete() {
        let filter = GMSAutocompleteFilter()
        filter.type = .city
        placesClient.autocompleteQuery(cityField.text!, bounds: nil, filter: filter, callback: {(results, error) -> Void in
            if let error = error {
                print("Autocomplete error \(error)")
                return
            }
            if let results = results {
                for result in results {
                    print("Result \(result.attributedPrimaryText)")
                }
            }
        })

    }

1 个解决方案

#1


2  

You are printing an attributed string. This should not appear when you display it in a UILable'sattributedText property. See my example below

您正在打印属性字符串。当您在UILable'sattributedText属性中显示它时,不应出现此问题。请参阅下面的示例

when you call for result in results save results in an array and reload the tableview by calling tableView.reloadData. In your tableView data source set the number of rows to the number of items in your array. Then inside cellForRowAtIndexPath do the following

当您在结果中调用结果时,将结果保存在数组中并通过调用tableView.reloadData重新加载tableview。在tableView数据源中,将行数设置为数组中的项数。然后在cellForRowAtIndexPath里面执行以下操作

let result = resultArray[indexPath.row] as? GMSAutocompletePrediction
cell.textLabel.attributedText = result.attributedPrimaryText

#1


2  

You are printing an attributed string. This should not appear when you display it in a UILable'sattributedText property. See my example below

您正在打印属性字符串。当您在UILable'sattributedText属性中显示它时,不应出现此问题。请参阅下面的示例

when you call for result in results save results in an array and reload the tableview by calling tableView.reloadData. In your tableView data source set the number of rows to the number of items in your array. Then inside cellForRowAtIndexPath do the following

当您在结果中调用结果时,将结果保存在数组中并通过调用tableView.reloadData重新加载tableview。在tableView数据源中,将行数设置为数组中的项数。然后在cellForRowAtIndexPath里面执行以下操作

let result = resultArray[indexPath.row] as? GMSAutocompletePrediction
cell.textLabel.attributedText = result.attributedPrimaryText