Ios ';在无效索引路径处请求rect';单元格点击时出现异常

Ios ';在无效索引路径处请求rect';单元格点击时出现异常,ios,swift,uitableview,indexpath,Ios,Swift,Uitableview,Indexpath,我正在使用自动填充功能搜索栏。有时在autofillTableView中点击单元格时会出现此错误: ***-[UITableViewRowData rectForRow:inSection:HeightCanBeguesed:]中的断言失败, /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3505.16/UITableViewRowData.m:1849 ***由于未捕获异常“NSInternalInconsist

我正在使用自动填充功能搜索栏。有时在autofill
TableView中点击单元格时会出现此错误:

***-[UITableViewRowData rectForRow:inSection:HeightCanBeguesed:]中的断言失败, /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3505.16/UITableViewRowData.m:1849

***由于未捕获异常“NSInternalInconsistencyException”而终止应用程序,原因:“请求在 无效的索引路径({length=2,path=0- 3} )'

如果我对这行注释
searchBar.text=cell.textlab!。text
应用程序不会崩溃

以下是完整的功能代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath)!
        address = cell.textLabel!.text!
        searchBar.text = cell.textLabel!.text
    }
我怎样才能修好它

UPD:看起来它在
searchBar.text=cell.textlab!之后崩溃了!。文本

我添加了
print(searchBar.text!)
并将正确的值打印到控制台

UPD2:只有当我在搜索栏中键入内容,然后点击屏幕上的某个位置关闭键盘,然后点击其中一个自动填充单元格时,应用程序才会崩溃

类别代码:

import UIKit
import Alamofire
import SwiftyJSON

class StreetSelectViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UINavigationControllerDelegate
{
    var data: [String] = ["Нет данных"]
    var filtered: [String] = []
    var searchActive : Bool = false

    @IBOutlet weak var cityNameLabel: UILabel!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var topSpaceConstraint: NSLayoutConstraint!
    @IBOutlet var gradientBackground: GradientView!

    let segueIdentifier = "ShowStreetSelectSegue"

    //background gradient
    override func viewDidLayoutSubviews()
    {
        self.gradientBackground.create()
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //side menu panGestureRecognizer
        if self.revealViewController() != nil
        {
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        tableView.delegate = self
        tableView.dataSource = self
        searchBar.delegate = self
        tableView.tableFooterView = UIView()
        navigationController?.delegate = self

        //search bar settings
        let barImage = UIImage()
        searchBar.setBackgroundImage(barImage, for: .any, barMetrics: .default)
        searchBar.scopeBarBackgroundImage = barImage
        searchBar.tintColor = UIColor.lightGray
        searchBar.setValue("Отмена", forKey:"_cancelButtonText")
        searchBar.showsCancelButton = false

        topSpaceConstraint.constant = self.navigationController!.navigationBar.frame.height + 8

        //network
        let queue = DispatchQueue(label: "com.admin.response-queue", qos: .utility, attributes: [.concurrent])
        URLCache.shared.removeAllCachedResponses()
        Alamofire.request("").validate()
            .responseJSON(
                queue: queue,
                completionHandler: { response in
                    if let JSON = response.result.value
                    {
                        self.data.removeAll()
                        let json = SwiftyJSON.JSON(JSON)
                        print("JSON: \(json)")
                        for (_, object) in json
                        {
                            self.data.append(object.stringValue)
                            print(self.data)
                        }
                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
            }
        )
    }

    override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }

    override func viewWillAppear(_ animated: Bool)
    {
        cityNameLabel.text = cityName
    }

    //MARK: - search bar settings
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)
    {
        searchActive = true;
        self.navigationController?.isNavigationBarHidden = true
        topSpaceConstraint.constant = 8
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar)
    {
        searchActive = false;
        self.navigationController?.isNavigationBarHidden = false
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
    {
        searchActive = false;
        filtered = data
        tableView.isHidden = false
        tableView.reloadData()
        topSpaceConstraint.constant = 8
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {    
        if !searchActive
        {
            searchActive = true
            tableView.reloadData()
        }

        self.searchBar.resignFirstResponder()
        address = searchBar.text!
        performSegue(withIdentifier: "ShowSearchResultsSeque", sender: Any?.self)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
    {
        filtered = data.filter({ (text) -> Bool in
            let tmp: NSString = text as NSString
            let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
            return range.location != NSNotFound
        })
        if(filtered.count == 0)
        {
            searchActive = false;
        }
        else
        {
            searchActive = true;
        }

        if searchText.characters.count != 0
        {
            tableView.isHidden = true
        }
        else
        {
            tableView.isHidden = false
        }

        tableView.reloadData()
        topSpaceConstraint.constant = 8
    }

    //MARK: - tableview settings

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if searchActive
        {
            if filtered.count == 0
            {
                return data.count
            }
            else
            {
                return filtered.count
            }
        }
        else
        {
            return data.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        if searchActive
        {
            if filtered.count == 0
            {
                cell.textLabel?.text = data.sorted()[indexPath.row]
            }
            else
            {
                cell.textLabel?.text = filtered.sorted()[indexPath.row]
            }
        }
        else
        {
            cell.textLabel?.text = data.sorted()[indexPath.row]
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let cell: UITableViewCell = self.tableView.cellForRow(at: indexPath)!
        address = cell.textLabel!.text!
        self.searchBar.text = cell.textLabel!.text
        print(searchBar.text!)          
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
    {
        cell.backgroundColor = UIColor.clear
        //text color
        cell.textLabel!.textColor = UIColor.white;
        //cell selection color
        let bgColorView = UIView()
        bgColorView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        cell.selectedBackgroundView = bgColorView
        tableView.backgroundColor = UIColor.clear
    }                 
}

为什么要使用
self.tableView.cellForRow
didSelectRowAt
方法中,您可以在
didSelectRowAt
方法中使用过滤后的数据源,您已经在
cellForRowAt
方法中使用过。您可以执行以下操作来实现您的功能

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        if searchActive
        {
            if filtered.count == 0
            {
                address = data.sorted()[indexPath.row]
            }
            else
            {
                address = filtered.sorted()[indexPath.row]
            }
            self.searchBar.text = address
        }         
    }

我不知道为什么,但问题出在
SearchDisplayController
中。在情节提要中删除后,一切正常

您需要使用数组,该数组用于设置cellI的
textlab
文本,仍然崩溃检查您的搜索栏<代码>出口是否与您的viewControllerIt已连接并将代理设置为Self是否单击tableview的最后一个单元格?应用程序不再崩溃,但自动填充仅在显示键盘时才起作用。当键盘隐藏时,应用程序不会对单元格点击做出反应。可能有什么问题?请再试一件事,删除
searchActive
boolean标志,并检查您的
filtered.count>0
是否为
address
self.searchBar
自动填充停止工作,因为当搜索栏/字段没有焦点时,您的
searchActive
false
。因此,您必须删除不必要的标志。并在
NSMutableArray
中维护单个数据源,这些数据源需要在所有位置使用,如
cellForRowAt
didSelectRowAt
。当您收到数据并在
textdichange
上更改数据时,请在
viewDidLoad
上填写它。这是一种比维护旗帜更简单的方法。谢谢您的帮助。我不知道为什么,但问题出在
SearchDisplayController
中。在情节提要中删除后,一切正常