在UISearchController的search栏上隐藏取消button
我试图隐藏在UISearchControllersearch栏的取消button,但不幸的是在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 }
这种方法的工作原理,但隐藏它之前会显示取消button,这是不理想的。 有什么build议么?
我build议按照build议子类化UISearchBar
和UISearchController
:
CustomSearchBar.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 } } }
在search栏隐藏取消button的委托方法,并设置你的委托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线程可能会帮助你在这个方向更多。