搜索结果不起作用去添加 tableviewcell

search result not work went add tableviewcell

在我添加自定义表格视图单元格之前,搜索栏运行良好。当我搜索与数组匹配的关键字时,它会中断。当我搜索错误时,它不会中断。

var filteredArray = [String]()
var searchController = UISearchController()
var result = UITableViewController()

override func viewDidLoad() {
    super.viewDidLoad()

    searchController = UISearchController(searchResultsController: result)
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self

    result.tableView.delegate = self
    result.tableView.dataSource = self
    result.tableView.register(UITableView.self, forCellReuseIdentifier: "Cell")

}

//config seachbar
func updateSearchResults(for searchController: UISearchController) {
    filteredArray = array.filter( { (array : String) -> Bool in
        if array.contains(searchController.searchBar.text!)
        {
            return true
        }
        else
        {
            return false
        }

    })
    result.tableView.reloadData()
}

这是一个表格视图 cellForRow

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SanPhamTableViewCell


    //    fill data into cell   
    if tableView == result.tableView
    {
        cell.name.text = filteredArray[indexPath.row]
        cell.img.image = UIImage(named:  ArrayImage[indexPath.row])

        cell.price.text = ArrayPrice[indexPath.row]
        cell.price.isUserInteractionEnabled = false

        cell.desc.text = arrayDesc[indexPath.row]
        cell.desc.isUserInteractionEnabled = false
    }
    else
    {
        cell.name.text = arrayName[indexPath.row]
        cell.img.image = UIImage(named:  arrayImage[indexPath.row])

        cell.price.text = arrayPrice[indexPath.row]
        cell.price.isUserInteractionEnabled = false

        cell.desc.text = arrayDesc[indexPath.row]
        cell.desc.isUserInteractionEnabled = false        }

    return cell
}

您需要像这样在viewDidLoad中注册单元格,替换为:

result.tableView.register(UITableView.self, forCellReuseIdentifier: "Cell")

与:

result.tableView.register(SanPhamTableViewCell.self, forCellReuseIdentifier: "Cell")

//

编辑 : for xib

result.tableView.register(UINib(nibName: "SanPhamTableViewCell", bundle: nil), forCellReuseIdentifier: Cell)

我不确定你是怎么做的 SanPhamTableViewCell,但是如果你使用的是自定义笔尖,那么该笔尖也必须在 tableView

中注册
result.tableView.register(UINib(nibName: "SanPhamTableViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")