iOS 13中Search Bar默认显示问题及旧行为恢复方法咨询
Hey there! Great question—this is a super common gotcha when migrating to iOS 13, so let's tackle both of your points clearly:
1. Is this the new default behavior in iOS 13?
Absolutely. Apple changed the default behavior of UISearchController when attached to a navigation item in iOS 13. In iOS 12 and earlier, assigning a search controller to navigationItem.searchController would default to hiding the search bar until the user scrolled down the table view. In iOS 13+, the search bar is visible by default as soon as the view controller loads. This was an intentional design change from Apple to make search more prominent in apps.
2. How to restore the iOS 12-style hidden-by-default behavior?
The fix is straightforward—you just need to explicitly set a single property on your navigation item to override the new default. Here's how to do it in code and via Storyboard:
Code Implementation (Swift)
In your UITableViewController's viewDidLoad method (or wherever you configure your search controller), add this line after assigning the search controller to the navigation item:
override func viewDidLoad() { super.viewDidLoad() // Configure your search controller as usual let searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false // Optional, based on your needs searchController.searchBar.placeholder = "Search items..." // Assign to navigation item navigationItem.searchController = searchController // Revert to iOS 12's hidden-by-default behavior navigationItem.hidesSearchBarWhenScrolling = true }
Storyboard Implementation
If you prefer using Storyboards:
- Select your
UITableViewController's navigation item (you'll find it in the document outline under the view controller) - Open the Attributes Inspector
- Look for the Hide Search Bar When Scrolling checkbox and tick it
This property tells the navigation bar to hide the search bar initially, only showing it when the user scrolls down the table view—exactly the behavior you had in iOS 12.
A quick note: Make sure you're targeting iOS 11 or later (which you likely are if you're migrating to iOS 13), since navigationItem.searchController was introduced in iOS 11.
Give that a shot, and your search bar should behave just like it did pre-iOS 13. If you hit any unexpected issues, feel free to follow up!
内容的提问来源于stack exchange,提问作者DaveDude

