将搜索栏添加到叠加层上的 ui table 视图

Adding a search bar to ui table view on overlay

我成功创建了一个深色叠加层,单击搜索图标并设法在深色叠加层上添加 table uiview,但现在想在其中添加一个搜索栏 table看法。我似乎无法弄清楚,因为我的代码似乎与其他人的示例不同。我是 swift 的新手,所以我的代码可能不是最干净的。我可以问一下是否有人可以告诉我如何做,因为我没有想法。我已经在下面发布了我的代码,有人可以告诉我哪里出错了。

非常感谢



class SearchLauncher: NSObject {

    let blackView = UIView()


    let tableView = UITableView()



    @objc func showSearch() {

        if let window = UIApplication.shared.keyWindow {

            blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)

            blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

            window.addSubview(blackView)

            window.addSubview(tableView)


            let height: CGFloat = 600
            let y = window.frame.height - height
            tableView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)

            blackView.frame = window.frame
            blackView.alpha = 0

            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

                self.blackView.alpha = 1

                self.tableView.frame = CGRect(x: 0, y: y, width: self.tableView.frame.width, height: self.tableView.frame.height)

            }, completion: nil)
        }



    }

    @objc func handleDismiss() {

        UIView.animate(withDuration: 0.5) {
            self.blackView.alpha = 0

            if let window = UIApplication.shared.keyWindow {
                self.tableView.frame = CGRect(x: 0, y: window.frame.height, width: self.tableView.frame.width, height: self.tableView.frame.height)
            }
        }


    }



    override init() {
        super.init()
        //start doing something here maybe

    }



}```

您是如何尝试添加搜索控制器的?

我会添加一个 UISearchController 作为 table 视图的 tableHeaderView。首先确保将 UISearchResultsUpdating 协议添加到您的 class.

class SearchLauncher: NSObject, UISearchResultsUpdating

然后将搜索栏添加到您的 table 视图

let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.sizeToFit()        
searchController.searchResultsUpdater = self

//you probably don't need this
//searchController.dimsBackgroundDuringPresentation = false

tableView.tableHeaderView = searchController.searchBar

然后,实现 updateSearchResults(for:_) 委托方法

func updateSearchResults(for searchController: UISearchController) {
    filteredTableData.removeAll(keepingCapacity: false)

    //filter the table data by using searchController.searchBar.text!
    //filteredTableData = ...

    self.tableView.reloadData()
}