UITableView 在调用 removeFromSuperView() 后仍然存在



我在视图控制器中有一个搜索栏,一旦用户单击回车键,它就会从 API 中提取搜索数据并使用数据初始化tableview

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

以下是setupTableView()函数:

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

现在,这是当用户单击搜索栏旁边的"取消"时调用的函数。

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

此函数中的所有代码都有效,除了

self.tableView.removeFromSuperView()  

用户仍可查看和单击表视图。我也尝试使用隐藏功能,但这也不起作用。我做错了什么?

你多次初始化表视图,你需要先检查表视图是否为零。试试这个:

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

最新更新