![](/img/trans.png)
[英]iOS8 Cannot hide cancel button on search bar in UISearchController
[英]Hiding Cancel button on search bar in UISearchController
我试图隐藏 UISearchController 中搜索栏的取消按钮,但不幸的是,在 viewDidLoad() 中设置以下内容不起作用:
override func viewDidLoad() {
super.viewDidLoad()
searchResultsTableController = UITableViewController()
searchResultsTableController.tableView.delegate = self
searchController = UISearchController(searchResultsController: searchResultsTableController)
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
searchResultsView.tableHeaderView = searchController.searchBar
searchController.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchBar.showsCancelButton = false
definesPresentationContext = true
}
我也试过在这个委托方法中使用上面的代码:
func didPresentSearchController(searchController: UISearchController) {
searchController.searchBar.showsCancelButton = false
}
这种方法有效,但会在隐藏之前短暂显示取消按钮,这并不理想。 有什么建议?
我最终按照建议对UISearchBar
和UISearchController
了子类化:
自定义搜索栏.swift
import UIKit
class CustomSearchBar: UISearchBar {
override func layoutSubviews() {
super.layoutSubviews()
setShowsCancelButton(false, animated: false)
}
}
CustomSearchController.swift
import UIKit
class CustomSearchController: UISearchController, UISearchBarDelegate {
lazy var _searchBar: CustomSearchBar = {
[unowned self] in
let result = CustomSearchBar(frame: CGRectZero)
result.delegate = self
return result
}()
override var searchBar: UISearchBar {
get {
return _searchBar
}
}
}
麾! 从 iOS 13 开始,可以访问UISearchController
上的automaticallyShowsCancelButton
。 将其设置为false
以隐藏取消按钮。
func didPresentSearchController(_ searchController: UISearchController) {
searchController.searchBar.becomeFirstResponder()
searchController.searchBar.showsCancelButton = true
}
func didDismissSearchController(_ searchController: UISearchController) {
searchController.searchBar.showsCancelButton = false
}
就我而言,上述所有解决方案都有效。 您需要在 didPresentSearchController 中显示并在 didDismissSearchController 中隐藏它。 早些时候我只是躲在 didDismissSearchController 中,它仍然在取消时显示取消按钮。
隐藏搜索栏委托方法中的取消按钮并设置您的委托searchController.searchBar.delegate=self
UISearchBarDelegate
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
}
尝试UISearchBar
并实现:
override func layoutSubviews() {
super.layoutSubviews()
self.setShowsCancelButton(false, animated: false)
}
这个SO 线程可能会在这个方向上为您提供更多帮助。
与@Griffith 和@Abhinav 给出的答案相同,但使用扩展名:
extension UISearchBar {
override open func layoutSubviews() {
super.layoutSubviews()
setShowsCancelButton(false, animated: false)
}
}
此代码来自 Swift 4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.