我已经在我的应用程序中添加了一个UISearchController,并将它的searchBar设置titleView为我的navigationItem.
这有效,但我看到了取消按钮,尽管设置showsCancelButton为false.
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = searchResultsUpdater
// Configure the searchBar
searchController.searchBar.placeholder = "Find Friends..."
searchController.searchBar.sizeToFit()
searchController.searchBar.showsCancelButton = false
self.definesPresentationContext = true
navigationItem.titleView = searchController.searchBar
Run Code Online (Sandbox Code Playgroud)

这似乎是iOS中的一个错误.我所描述的相同行为可以在Apple提供的示例项目中看到
文档说明了默认值,NO但似乎并非如此.设置showsCancelButton到NO似乎没有任何效果.
我为此提出了雷达,我正等着收听.
Swift3中的简单解决方案- 我们需要使用CustomSearchBar而不使用取消按钮,然后覆盖新CustomSearchController中的相应属性:
class CustomSearchBar: UISearchBar {
override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) {
super.setShowsCancelButton(false, animated: false)
}}
class CustomSearchController: UISearchController {
lazy var _searchBar: CustomSearchBar = {
[unowned self] in
let customSearchBar = CustomSearchBar(frame: CGRect.zero)
return customSearchBar
}()
override var searchBar: UISearchBar {
get {
return _searchBar
}
}}
Run Code Online (Sandbox Code Playgroud)
在MyViewController中,我使用这个新的自定义子类初始化和配置searchController:
var mySearchController: UISearchController = ({
// Display search results in a separate view controller
// let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
// let alternateController = storyBoard.instantiateViewController(withIdentifier: "aTV") as! AlternateTableViewController
// let controller = UISearchController(searchResultsController: alternateController)
let controller = CustomSearchController(searchResultsController: nil)
controller.searchBar.placeholder = NSLocalizedString("Enter keyword (e.g. iceland)", comment: "")
controller.hidesNavigationBarDuringPresentation = false
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.sizeToFit()
return controller
})()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5443 次 |
| 最近记录: |