Dung Tien
Dung Tien

Reputation: 15

search result not work went add tableviewcell

Search bar is woking very well until I add custom tableview cell. It breaks when I search a keyword matching with a array. When I search wrong, it doesn't break.

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()
}

and this is a tableview 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
}

this is a error

Upvotes: 1

Views: 53

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need to register the cell like this in viewDidLoad, replace:

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

with:

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

//

Edit : for xib

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

Upvotes: 1

ODev99
ODev99

Reputation: 34

I am not sure how are you making the SanPhamTableViewCell, But if you are using a custom nib then that nib must also be registered with tableView

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

Upvotes: 0

Related Questions