Проблема обновления значения источника данных TableView - PullRequest
0 голосов
/ 28 июня 2018

У меня есть приложение, в котором пользователь может искать местоположение из панели поиска. При поиске пользователем в любом месте результаты отображаются в виде таблицы под строкой поиска. Приходит проблема, что, когда я ищу в любом месте, это дает результат, но не отображается в табличном представлении. Я проверил делегат и источник данных, они правильно подключены, но табличное представление не показывает никаких данных. Как я могу получить эти данные в виде таблицы. Я использовал точку останова, и она не перехватывает точку останова. Это код, как я получаю результаты поиска,

extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {

    guard let mapView = mapView,
        let searchBarText = searchController.searchBar.text else { return }
    print(searchBarText)
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = searchBarText
    request.region = mapView.region
    let search = MKLocalSearch(request: request)
    print(search)
    search.start { response, _ in
        guard let response = response else {
            return
        }
        self.matchingItems = response.mapItems
        print(self.matchingItems)
        self.tableView.reloadData()
    }
}

Здесь я передаю результаты поиска в табличное представление,

extension LocationSearchTable {

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return matchingItems.count
}

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    print(  cell.textLabel?.text)
    cell.detailTextLabel?.text = parseAddress(selectedItem: selectedItem)
    print( cell.detailTextLabel?.text)
    return cell
}

} Это ответ, который я получаю при поиске в любом месте,

[<MKMapItem: 0x1c434d5d0> {
isCurrentLocation = 0;
name = California;
placemark = "California, California, United States @ <+37.13374180,-120.28640480> +/- 0.00m, region CLCircularRegion (identifier:'<+37.41896824,-119.30660700> radius 706259.58', center:<+37.41896824,-119.30660700>, radius:706259.58m)";
timeZone = "America/Los_Angeles (GMT-7) offset -25200 (Daylight)";

}]

Это весь код моего файла swift,

// weak var delegate: HandleMapSearch?
var matchingItems: [MKMapItem] = []
var mapView: MKMapView?
 func parseAddress(selectedItem:MKPlacemark) -> String {

    // put a space between "4" and "Melrose Place"
    let firstSpace = (selectedItem.subThoroughfare != nil &&
                        selectedItem.thoroughfare != nil) ? " " : ""

    // put a comma between street and city/state
    let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) &&
                (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""

    // put a space between "Washington" and "DC"
    let secondSpace = (selectedItem.subAdministrativeArea != nil &&
                        selectedItem.administrativeArea != nil) ? " " : ""

    let addressLine = String(
        format:"%@%@%@%@%@%@%@",
        // street number
        selectedItem.subThoroughfare ?? "",
        firstSpace,
        // street name
        selectedItem.thoroughfare ?? "",
        comma,
        // city
        selectedItem.locality ?? "",
        secondSpace,
        // state
        selectedItem.administrativeArea ?? ""
    )

    return addressLine
}

1 Ответ

0 голосов
/ 28 июня 2018

Вам необходимо установить делегат и источник данных в viewDidLoad

tableView.delegate = self
tableView.dataSource = self   

и правильно реализовать методы, как это

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {t {
    return matchingItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    print(  cell.textLabel?.text)
    cell.detailTextLabel?.text = parseAddress(selectedItem: selectedItem)
    print( cell.detailTextLabel?.text)
    return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  return 100
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...