gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:06 25 4
gpt4 key购买 nike

使用 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
}

}

截图

enter image description here

最佳答案

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

如果您想隐藏搜索栏,请记住将部分标题的高度保持为 0.1。保持高度 0 无效。

关于ios - 如何通过点击导航栏按钮显示和隐藏 tableView 部分中的标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com