8

我希望能够将个人位置附加到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
    }
}
4

1 回答 1

5

我不认为您可以将自己的位置和 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
}
于 2017-10-25T08:38:51.250 回答