单击导航栏中的右栏按钮项时是否打开搜索栏?

时间:2020-02-04 07:34:52

标签: swift

**** open a search bar when i click on right navigation bar button action.****

i have  a view controller and on the right side of  the controller there is a search bar button item so on the action of button i want to open a search bar.

所以我不知道如何在单击按钮时打开搜索 谢谢。

1 个答案:

答案 0 :(得分:0)

如果使用UITableView,则可以将UISearchBar添加到UITableView的tableViewHeader属性。您可以通过更改UITableView contentOffset属性来显示UISearchBar。下面是一个基本示例:

final class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var tableView: UITableView!
@IBOutlet var searchBarButtonItem: UIBarButtonItem!

private let datasource = ["data1", "data2", "data3", "data4", "data5", "data6"]

private lazy var dataSearchBar: UISearchBar = {
    let searchBar = UISearchBar(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: 44.0))
    searchBar.placeholder = "Search..."
    return searchBar
}()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableHeaderView = dataSearchBar
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    var contentOffset = self.tableView.contentOffset
    contentOffset.y = contentOffset.y + (self.tableView.tableHeaderView?.frame ?? CGRect()).height
    self.tableView.contentOffset = contentOffset
}

@IBAction func didTap(searchBarbuttonItem barButtonItem: UIBarButtonItem) {
    let indexPath = IndexPath(item: 1, section: 0)
    tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    datasource.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

    cell.textLabel?.text = datasource[indexPath.row]

    return cell
}

}

UI Preview