iOS开发:点击导航栏按钮切换TableView分区表头的显示与隐藏
Hey there! Let's get that sticky, toggleable search bar sorted out for your iOS app. Here's a step-by-step solution tailored to your setup with Xcode 9.3 and Swift:
1. Declare Required Properties
First, add these properties to your TableViewController class to manage the search bar and its visibility state:
import UIKit class TableViewController: UITableViewController, UISearchBarDelegate { // Add delegate if you need search functionality private let searchBar = UISearchBar() private var isSearchBarVisible = false // Rest of your existing code... }
2. Set Up Navigation Bar Toggle Button & Search Bar
In viewDidLoad, configure the nav bar button to trigger the show/hide action and set up the search bar's initial state:
override func viewDidLoad() { super.viewDidLoad() // Add toggle button to navigation bar let toggleSearchButton = UIBarButtonItem(title: "Search", style: .plain, target: self, action: #selector(toggleSearchBarVisibility)) navigationItem.rightBarButtonItem = toggleSearchButton // Configure search bar appearance and behavior searchBar.placeholder = "Search your items..." searchBar.sizeToFit() searchBar.delegate = self // Assign delegate if you need to handle search events // Initial state: hide the search bar searchBar.isHidden = true }
3. Implement Toggle Functionality
Add the selector method to switch the search bar's visibility and refresh the table view section to reflect the change:
@objc private func toggleSearchBarVisibility() { isSearchBarVisible.toggle() searchBar.isHidden = !isSearchBarVisible // Refresh the first section to update header height and visibility tableView.reloadSections(IndexSet(integer: 0), with: .automatic) }
4. Make the Search Bar Sticky & Control Header Height
Override these table view delegate methods to ensure the search bar stays visible during scrolling (works with plain-style table views) and adjusts the header height based on visibility:
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Return 0 height when search bar is hidden to avoid empty space return isSearchBarVisible ? searchBar.frame.height : 0 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // Return the search bar as the section header return searchBar }
Key Notes
- Sticky Header Requirement: Ensure your table view uses the Plain style (not Grouped) in the storyboard or via code (
UITableView(frame: .zero, style: .plain)). Grouped table views don't support sticky section headers. - Search Functionality: If you need to handle search queries, implement the
UISearchBarDelegatemethods likesearchBar(_:textDidChange:)to filter your table data. - Customization: You can adjust the search bar's style (e.g.,
searchBar.searchBarStyle = .minimal) or add a background view to the header for better visual integration.
内容的提问来源于stack exchange,提问作者TakeYourMark

