Dan Li
Dan Li

Reputation: 45

searchBar Function But TableView Fatal error

I build search bar in my tableview, everything works fine, Search function is all good, If I enter text on searchBar, Shows search result correctly in tableView. But here is the problem: When you Run this app at first time, And press directly on tableview then it comes to a fatal error.The problem comes only when I first run the app and without writing something in searchBar and press directly on tableview menu. I'm little bit confused,Below you can see my code. How can fix it? Thanks in advance.

enter image description here

import UIKit

var searchController:UISearchController=UISearchController()

@IBOutlet weak var TableView: UITableView!

@IBOutlet var infoView: UIView!

@IBOutlet weak var infoImage: UIImageView!

@IBOutlet weak var infoNameLabel: UILabel!

@IBOutlet weak var dimView: UIView!


@IBAction func closeInfoPopup(_ sender: Any) {

    UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
        self.dimView.alpha = 0
        self.infoView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
    }) { (success) in
        self.infoView.removeFromSuperview()
    }
}

 override func viewDidLoad() {
    super.viewDidLoad()
    configureSearchController()

    Data.getData { (data) in
        self.tableData=data
        self.TableView.reloadData()

    }
    TableView.delegate=self
    TableView.dataSource=self
}

func updateSearchResults(for searchController: UISearchController) {

        if let searchText = searchController.searchBar.text, !searchText.isEmpty {
            filteredArray = tableData.filter { data in
                return data.name.lowercased().contains(searchText.lowercased())
            }

        } else {
            filteredArray = tableData
        }
        TableView.reloadData()
    }

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    if !shouldShowSearchResults{
        shouldShowSearchResults = true
        TableView.reloadData()
    }
    searchController.searchBar.resignFirstResponder()
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    shouldShowSearchResults = true
    TableView.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    shouldShowSearchResults = false
    TableView.reloadData()
}

func configureSearchController(){
    searchController=UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater=self
    searchController.dimsBackgroundDuringPresentation=false
    searchController.searchBar.placeholder="Search here..."
    searchController.searchBar.delegate=self
    searchController.searchBar.sizeToFit()

    TableView.tableHeaderView = searchController.searchBar
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let data=tableData[indexPath.row]
    let filteredData=filteredArray[indexPath.row]

    if shouldShowSearchResults == true{
        infoImage.image=filteredData.image
        infoNameLabel.text=filteredData.name
        infoView.center=view.center
        view.addSubview(infoView)
    }else{
        infoImage.image=data.image
        infoNameLabel.text=data.name
        infoView.center=view.center
        view.addSubview(infoView)
    }
    infoView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2)
    UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
        self.dimView.alpha=0.8
        self.infoView.transform = .identity
    })
    }




func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 160
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if shouldShowSearchResults{
        return filteredArray.count
    }else{
        return tableData.count
    }

}

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

    if shouldShowSearchResults{
        cell.setup(modeleData: filteredArray[indexPath.row])
    }else{
        cell.setup(modeleData: tableData[indexPath.row])
    }

    return cell
}

}

Upvotes: 0

Views: 38

Answers (1)

Bhavin Kansagara
Bhavin Kansagara

Reputation: 2916

You should update your didSelectRowAt Method to this, because initially you have no object in the filteredData and you are trying to get the data at indexPath.row from it, that leads to the crashing.

let data=tableData[indexPath.row]
let filteredData=filteredArray[indexPath.row]

These two lines should be moved to specific conditions. Look at the following code.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

if shouldShowSearchResults == true{
    let filteredData=filteredArray[indexPath.row]

    infoImage.image=filteredData.image
    infoNameLabel.text=filteredData.name
    infoView.center=view.center
    view.addSubview(infoView)
}else{
    let data=tableData[indexPath.row]

    infoImage.image=data.image
    infoNameLabel.text=data.name
    infoView.center=view.center
    view.addSubview(infoView)
}
infoView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
    self.dimView.alpha=0.8
    self.infoView.transform = .identity
})
}
}

Upvotes: 1

Related Questions