我希望能够在用户搜索搜索栏时可以找到的个人位置附加到MKLocationSearchCompletion
array
中。但是,我无法理解如何将项目存储到对象中,以及是否可以将地标对象(或位置信息)添加到MKLocationSearch
对象中。我从文档中能够获得的是,MKLocalSearchCompleter
对象存储当用户在搜索栏中键入部分字符串时访问的字符串。但我不确定在哪里可以访问此阵列并添加新位置。
下面是代码的结构以显示搜索完成结果:
var searchCompleter = MKLocalSearchCompleter()
var searchResults = [MKLocalSearchCompletion]()
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
searchCompleter.delegate = self
searchBar.delegate = self
}
extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
searchResults = completer.results
searchResultsTableView.reloadData()
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
// handle error
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let searchResult = searchResults[indexPath.row]
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.textLabel?.attributedText = highlightedText(searchResult.title, inRanges: searchResult.titleHighlightRanges, size: 17.0)
cell.detailTextLabel?.attributedText = highlightedText(searchResult.subtitle, inRanges: searchResult.subtitleHighlightRanges, size: 12.0)
return cell
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchCompleter.queryFragment = searchText
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
self.searchBar.endEditing(true)
searchBar.resignFirstResponder()
return true
}
}
我不认为您可以将自己的位置和POI添加到MapKit中,但是:
1)我建议你创建一个自己的枚举
class CustomSearchResult {
let title: String
...
}
enum SearchResultType {
case localSearchResult(result: MKLocalSearchCompletion)
case customResult(result: CustomSearchResult)
}
2)你有你的结果数组:
var searchResults = [SearchResultType]()
3)在completerDidUpdateResults
中,您可以将个人结果和MapKit结果添加到searchResults
数组中:
searchResults = completer.results.map {
SearchResultType.localSearchResult(result: $0) }
// Add here custom results
searchResults.append(SearchResultType.customResult(result:
CustomSearchResult(title: "test")))
4) ..在cellForRowAtIndexPath
中,您可以决定是自定义结果还是 MapKit 结果:
let searchResult = searchResults[indexPath.row]
switch searchResult {
case .customResult(let result):
cell.textLabel.text = result.title
case .localSearchResult(let result):
cell.textLabel.text = result.title
}