无法将行插入 UITableView - Swift 3 [英] Cant insert rows into UITableView - Swift 3

查看:16
本文介绍了无法将行插入 UITableView - Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码导致应用程序因错误而崩溃:

I have the following code which causes the app to crash with the error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

我尝试了 StackOverflow 上列出的多种解决方案,但没有一个可以阻止此错误.

I have tried multiple solutions as listed on StackOverflow but none can stop this error.

尝试过:

代码:

import UIKit
import MapKit

class TableViewController: UITableViewController, UISearchResultsUpdating {

    var localSearchRequest:MKLocalSearchRequest!
    var localSearch:MKLocalSearch!
    var localSearchResponse:MKLocalSearchResponse!
    var locations = [MKMapItem]()

    @available(iOS 8.0, *)
    public func updateSearchResults(for searchController: UISearchController) {
        localSearch?.cancel()
        localSearchRequest = MKLocalSearchRequest()
        localSearchRequest.naturalLanguageQuery = searchController.searchBar.text
        localSearch = MKLocalSearch(request: localSearchRequest)
        localSearch.start { (localSearchResponse, error) -> Void in
            if localSearchResponse != nil {
                let toNum = localSearchResponse?.mapItems.count ?? 0
                for i in stride(from: 0, to: toNum, by: 1) {
                    self.locations.append((localSearchResponse?.mapItems[i])!)
                    print((localSearchResponse?.mapItems[i])!)
                }
                self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation(rawValue: 5)! )
            }
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
        let row = indexPath.row
        cell.textLabel?.text = self.locations[row].name
        return cell
    }

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
        searchController.searchBar.tintColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
        searchController.searchBar.placeholder = "Location"
        searchController.searchBar.returnKeyType = UIReturnKeyType(rawValue: 6)!
        self.tableView.tableHeaderView = searchController.searchBar
    }

    override func viewDidDisappear(_ animated: Bool) {
        searchController.searchBar.isHidden = true
    }
}

<小时>

使用 vadian 建议的新 localSearch.start 如下:

localSearch.start { (localSearchResponse, error) -> Void in
        if let response = localSearchResponse {
            self.locations.removeAll()
            for mapItem in response.mapItems {
                self.locations.append(mapItem)
                print(mapItem)
            }
            if !response.mapItems.isEmpty {
                let indexPaths = (0..<response.mapItems.count).map { IndexPath(row: $0, section: 0) }
                self.tableView.insertRows(at: indexPaths, with: .none)
            }
        }
    }

这仍然产生同样的错误,
尝试将第 0 行插入第 0 节,但更新后第 0 节中只有 0 行 .
任何帮助将不胜感激

This still produces the same error,
attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update .
Any help will be appreciated

推荐答案

您的代码有两个主要问题:

Your code got two major issues:

  • 即使地图项数为 0,也会插入一行.(这导致了错误).
  • 如果有多个地图项,也只会插入一行.

尝试这样的事情

    if let response = localSearchResponse { 
        for mapItem in response.mapItems { // please not those ugly C-stlye loops
           self.locations.insert(mapItem, at:0)
           print(mapItem)
        }
        if !response.mapItems.isEmpty {
            let indexPaths = (0..<response.mapItems.count).map { IndexPath(row: $0, section: 0) }
            self.tableView.insertRows(at: indexPaths, with: .none )
        }
    }

注意:UITableViewRowAnimation(rawValue: 5)!.none 完全一样,后者更短,描述性更强.

Note: UITableViewRowAnimation(rawValue: 5)! and .none is exactly the same, the latter is much shorter and dramatically more descriptive.

但由于您根本不想使用行动画,我建议

But as you don't want to use row animation at all I'd recommend

    if let response = localSearchResponse { 
        for mapItem in response.mapItems {
           self.locations.append(mapItem)
           print(mapItem)
        }
        self.tableView.reloadData()
    }

这篇关于无法将行插入 UITableView - Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆