tjc
tjc

Reputation: 37

UITableView still present after calling removeFromSuperView()

I have a search bar in a view controller that once the user clicks enter, it pulls the search data from an API and initializes a tableview with the data.

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {

    setupTableView()

    UIView.animate(withDuration: 0.3, animations: {

        self.searchLabel.removeFromSuperview()
        self.searchBar.center = CGPoint(x: self.searchBar.frame.midX, y: 40)
        self.tableView.frame = CGRect(x: 0, y: 25 + searchBar.frame.size.height, width: self.view.frame.width, height: self.view.frame.height - (25 + searchBar.frame.height) - (self.tabBarController?.tabBar.frame.size.height)!)

    })

    searchBar.setShowsCancelButton(true, animated: true)
}

Here is the setupTableView() function:

func setupTableView() {

    tableView = UITableView(frame: CGRect(x: 0, y: 44 + searchLabel.frame.height + searchBar.frame.size.height, width: view.frame.width, height: view.frame.height - (44 + searchLabel.frame.height + searchBar.frame.size.height) - (self.tabBarController?.tabBar.frame.size.height)!))
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(SearchCell.self, forCellReuseIdentifier: "TableViewCell")
    frame = tableView.frame
    tableView.tableFooterView = UIView()
    view.addSubview(tableView)

}

Now here is the function that is called when the user clicks Cancel next to the search bar.

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

    searchBar.text = ""
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.endEditing(true)
    self.tableView.removeFromSuperview()
    view.addSubview(searchLabel)

    UIView.animate(withDuration: 0.3, animations: {

        searchBar.center = self.center

    })
}

All the code in this function works, except the

self.tableView.removeFromSuperView()  

The tableview is still visible and clickable by the user. I have also tried using the hide function, but that does not work either. What am I doing wrong?

Upvotes: 0

Views: 224

Answers (1)

Kevinosaurio
Kevinosaurio

Reputation: 2010

You init the tableView several times, you need to check if the tableView is nil first. Try with this:

func setupTableView() {

    if tableView == nil
    {
       tableView = UITableView(frame: CGRect(x: 0, y: 44 + searchLabel.frame.height + searchBar.frame.size.height, width: view.frame.width, height: view.frame.height - (44 + searchLabel.frame.height + searchBar.frame.size.height) - (self.tabBarController?.tabBar.frame.size.height)!))
       tableView.delegate = self
       tableView.dataSource = self
       tableView.register(SearchCell.self, forCellReuseIdentifier: "TableViewCell")
       frame = tableView.frame
       tableView.tableFooterView = UIView()
    }

    if(!tableView.isDescendant(of: view)) {
       self.view.addSubview(tableView)
    }
}

Upvotes: 1

Related Questions