在叠加层的ui表格视图中添加搜索栏

时间:2019-06-05 21:11:28

标签: swift uiview uisearchbar

我设法创建了一个黑暗的覆盖层,一旦单击搜索图标,并设法在该黑暗的覆盖层上添加了一个表uiview,但是现在想在该表视图内添加一个搜索栏。我似乎无法弄清楚,因为我的代码似乎与其他所有人的示例不同。我是新手,所以我的代码可能不是最干净的。我可以问问别人是否可以告诉我该怎么做,因为我没有主意。我在下面发布了我的代码,有人可以告诉我我要去哪里了。

非常感谢



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

    }



}```

1 个答案:

答案 0 :(得分:0)

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

我可以通过将UISearchController添加为表视图的tableHeaderView来实现。首先,请确保将UISearchResultsUpdating协议添加到您的课程中。

class SearchLauncher: NSObject, UISearchResultsUpdating

然后将搜索栏添加到表格视图

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