我希望能够将个人位置附加到MKLocationSearchCompletion数组中,当用户搜索搜索栏时可以找到该数组.但是,我无法理解项目如何存储到对象中以及是否可以将地标对象(或位置信息)添加到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,但是:
原文链接:https://www.f2er.com/swift/319322.html1)我建议你创建一个自己的枚举
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 }