我希望能够在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
}
}
答案 0 :(得分:5)
我认为您不能将自己的位置和兴趣点添加到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
}