如何通过点击导航栏按钮来显示和隐藏tableView部分中的标题?

以你的标记

使用Xcode 9.3版Swift开发iOS应用程序。

您能告诉我如何通过点击导航栏按钮来显示和隐藏(切换)tableView部分的标题吗?

  • 搜索栏放在节的标题中,以使其在滚动tableview时始终可见
  • 我想在初始显示中隐藏搜索栏
  • 然后,通过点击导航栏按钮来显示和隐藏搜索栏

代码和屏幕截图如下。

import UIKit

class TableViewController: UITableViewController, UISearchBarDelegate {

    let array = ["apple", "orange", "melon", "banana", "peach"]
    let searchBar = UISearchBar()

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchButton = UIBarButtonItem(title: "Search", style: UIBarButtonItemStyle.plain, target: self, action: #selector(searchTapped))
        self.navigationItem.leftBarButtonItem = searchButton
    }

    @objc func searchTapped() {
        // If searchBar is hidden, then show a searchBar.

        // If searchBar is shown, then hide a searchBar.

    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        searchBar.delegate = self
        searchBar.placeholder = "Search..."
        searchBar.showsCancelButton = true
        return searchBar
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        searchBar.sizeToFit()
        return searchBar.frame.height
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }

}

屏幕截图

在此处输入图片说明

尼蒂什
var hideSearchBar = false     // Class global var

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     return hideSearchBar ? 0.1 : searchBarHeight
}  

@IBAction func search(sender: UIBarButtonItem) {
     hideSearchBar = !hideSearchBar
     tableView.reloadData()
} 

如果要隐藏searchBar,请记住将节标题的高度保持为0.1保持高度0不起作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章