以下內(nèi)容是在 Swift 4.0蚯涮,iOS 11 下的運(yùn)行結(jié)果
如果傳入的searchresultscontroller為nil拓颓,則表示搜索的結(jié)果在當(dāng)前控制器中顯示溉躲,現(xiàn)在我讓它在searchresultvc中顯示
默認(rèn)樣式
初始化一個(gè) UISearchController星岗,并將 searchBar 設(shè)置為 tableView 的 headerView 時(shí),如以下代碼:
let searchController = UISearchController.init(searchResultsController: nil)
tableView.tableHeaderView = searchController.searchBar
自定義
下面我們通過(guò)修改 searchController 的 searchBar 屬性來(lái)調(diào)整樣式首有。
1. searchBarStyle
搜索框樣式
public enum UISearchBarStyle : UInt {
? ? case `default` // 默認(rèn)樣式燕垃,和 UISearchBarStyleProminent 一樣
? ? case prominent // 顯示背景,常用在my Mail, Messages and Contacts
? ? case minimal // 不顯示背景井联,系統(tǒng)自帶的背景色無(wú)效卜壕,自定義的有效,常用在Calendar, Notes and Music
}
用例:
letsearchBar = searchController.searchBar
searchBar.searchBarStyle = .default
2. tintColor
風(fēng)格顏色烙常,可用于修改:
輸入框的光標(biāo)顏色
取消按鈕字體顏色
選擇欄被選中時(shí)的顏色
letsearchBar = searchController.searchBar
searchBar.tintColor = .red
3. barTintColor
搜索框背景顏色
letsearchBar = searchController.searchBar
searchBar.barTintColor = .orange
4. backgroundImage
搜索框背景圖片
createImage(_:size:)?方法為創(chuàng)建一個(gè)指定顏色轴捎,指定 size 的圖片。
letsearchBar = searchController.searchBar
searchBar.backgroundImage = self.createImage(UIColor.red, size: CGSize.init(width: 200, height: 100))
5. 設(shè)置(獲染唷)搜索框背景圖片
可以通過(guò)以下方式設(shè)置(獲嚷滞伞)搜索框背景圖片:
// 設(shè)置
// Use UIBarMetricsDefaultPrompt toseta separate backgroundImagefora search bar with a prompt
funcsetBackgroundImage(_ backgroundImage: UIImage?,forbarPosition: UIBarPosition, barMetrics: UIBarMetrics)
// 獲取
open func backgroundImage(forbarPosition: UIBarPosition, barMetrics: UIBarMetrics) -> UIImage?
public enum UIBarMetrics : Int {
? ? case `default`
? ? case compact
? ? case defaultPrompt // Applicable only in bars with the prompt property, such as UINavigationBar and UISearchBar
? ? case compactPrompt
? ? @available(iOS, introduced: 5.0, deprecated: 8.0, message: "Use UIBarMetricsCompact instead")
? ? public static var landscapePhone: UIBarMetrics { get }
? ? @available(iOS, introduced: 7.0, deprecated: 8.0, message: "Use UIBarMetricsCompactPrompt")
? ? public static var landscapePhonePrompt: UIBarMetrics { get }
}
@available(iOS 7.0, *)
public enum UIBarPosition : Int {
? ? case any
? ? case bottom // The bar is at the bottom of its local context, and directional decoration draws accordingly (e.g., shadow above the bar).
? ? case top // The bar is at the top of its local context, and directional decoration draws accordingly (e.g., shadow below the bar)
? ? case topAttached // The bar is at the top of the screen (as well as its local context), and its background extends upward—currently only enough for the status bar.
}
用例:
letsearchBar = searchController.searchBar
searchBar.setBackgroundImage(createImage(.blue, size: CGSize.init(width: 20, height: 20)),for: .any, barMetrics: .default)
6. 文本框的背景圖片
open funcsetSearchFieldBackgroundImage(_ backgroundImage: UIImage?,forstate: UIControlState)
open func searchFieldBackgroundImage(forstate: UIControlState) -> UIImage?
letsearchBar = searchController.searchBar
searchBar.setSearchFieldBackgroundImage(createImage(UIColor.yellow, size: CGSize.init(width: 200, height: 40)),for: .normal)
7. barStyle
搜索框風(fēng)格 barStyle 的類型為 UIBarStyle,定義如下:
public enum UIBarStyle : Int {
case`default`
caseblack
}
用例:
letsearchBar = searchController.searchBar
searchBar.barStyle = .black
8. showsBookmarkButton
是否顯示搜索框右側(cè)的圖書(shū)按鈕蝗锥。
open var showsBookmarkButton: Bool // default is NO
9. showsCancelButton
是否顯示搜索框右側(cè)的取消按鈕跃洛。
open var showsCancelButton: Bool // default is NO
10. showsSearchResultsButton
是否顯示搜索框右側(cè)的搜索結(jié)果按鈕:
open var showsSearchResultsButton: Bool // default is NO
11. isSearchResultsButtonSelected
設(shè)置搜索結(jié)果按鈕為選中狀態(tài):
open var isSearchResultsButtonSelected: Bool // default is NO
用例:
letsearchBar = searchController.searchBar
searchBar.showsSearchResultsButton =true
searchBar.isSearchResultsButtonSelected =true
12. searchFieldBackgroundPositionAdjustment
設(shè)置輸入框背景偏移量:
open var searchFieldBackgroundPositionAdjustment: UIOffset
用例:
letsearchBar = searchController.searchBar
searchBar.searchFieldBackgroundPositionAdjustment = UIOffset.init(horizontal: 16, vertical: 16)
13. searchTextPositionAdjustment
設(shè)置輸入框文本偏移量:
open var searchTextPositionAdjustment: UIOffset
用例:
letsearchBar = searchController.searchBar
searchBar.searchTextPositionAdjustment = UIOffset.init(horizontal: 16, vertical: 16)
14. 設(shè)置(獲取)搜索框的圖標(biāo)
可以設(shè)置(獲戎找椤)的搜索框圖標(biāo)包括:
搜索圖標(biāo)
清除輸入的文字的圖標(biāo)
圖書(shū)圖標(biāo)
搜索結(jié)果列表圖標(biāo)
open funcsetImage(_ iconImage: UIImage?,foricon: UISearchBarIcon, state: UIControlState)
open func image(foricon: UISearchBarIcon, state: UIControlState) -> UIImage?
letsearchBar = searchController.searchBar
searchBar.showsBookmarkButton =true
letsearchImage = self.createImage(.red, size: CGSize.init(width: 20, height: 20))
letclearImage = self.createImage(.yellow, size: CGSize.init(width: 20, height: 20))
letbookmarkImage = self.createImage(.blue, size: CGSize.init(width: 20, height: 20))
letresultsListImage = self.createImage(.orange, size: CGSize.init(width: 20, height: 20))
searchBar.setImage(searchImage,for: .search, state: .normal)
searchBar.setImage(clearImage,for: .clear, state: .normal)
searchBar.setImage(bookmarkImage,for: .bookmark, state: .normal)
searchBar.setImage(resultsListImage,for: .resultsList, state: .normal)
15. 設(shè)置(獲然憬摺)搜索框的圖標(biāo)的偏移量
除了可以設(shè)置(獲却谢取) 14 中的圖片,還可以設(shè)置(獲认噶恰)的偏移量两曼。
open funcsetPositionAdjustment(_ adjustment: UIOffset,foricon: UISearchBarIcon)
open func positionAdjustment(foricon: UISearchBarIcon) -> UIOffset
用例:
letsearchBar = searchController.searchBar
searchBar.setPositionAdjustment(UIOffset.init(horizontal: 10, vertical: 10),for: .search)
16. 顯示(隱藏)取消按鈕
可以用以下方法設(shè)置顯示(隱藏)取消按鈕:
open funcsetShowsCancelButton(_ showsCancelButton: Bool, animated: Bool)
當(dāng)我們希望徹底隱藏掉取消按鈕的時(shí)候,應(yīng)該怎么做呢玻驻?經(jīng)過(guò)測(cè)試發(fā)現(xiàn)悼凑,只有在?UISearchController?的?delegate?中的?didPresentSearchController(_)?實(shí)現(xiàn)內(nèi)調(diào)用可以實(shí)現(xiàn)隱藏取消按鈕。
extension ViewController: UISearchControllerDelegate {
? ? func didPresentSearchController(_ searchController: UISearchController) {
searchController.searchBar.setShowsCancelButton(false, animated:false)
? ? }
}
效果如下:
可以發(fā)現(xiàn)取消按鈕先顯示了一下璧瞬,然后隱藏了户辫,效果并不理想。如果想徹底隱藏取消按鈕嗤锉,有一種方法是繼承?UISearchController?和?UISearchBar?實(shí)現(xiàn)自定義渔欢。代碼如下
// 自定義 UISearchBar
class CustomSearchBar: UISearchBar {
override funclayoutSubviews() {
? ? ? ? super.layoutSubviews()
setShowsCancelButton(false, animated:false)
? ? }
}
// 自定義 UISearchController
class CustomSearchController: UISearchController {
lazy var _searchBar: CustomSearchBar = { [unowned self]in
letresult = CustomSearchBar(frame: CGRect.zero)
? ? ? ? result.delegate = self
returnresult
? ? }()
? ? override var searchBar: UISearchBar {
return_searchBar
? ? }
}
extension CustomSearchController: UISearchBarDelegate {
}
使用自定義的?CustomSearchController?可以完全隱藏取消按鈕,效果如下:
17. 設(shè)置取消按鈕的名稱
可以通過(guò)以下幾個(gè)方法修改取消按鈕的名稱:
方法一:(已失效)
letsearchBar = searchController.searchBar
searchBar.setValue("Done",forKey:"_cancelButtonText")
方法二:
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title ="Done"
方法三:
letsearchBar = searchController.searchBar
searchBar.showsCancelButton =true
letcancelButton = searchBar.value(forKey:"cancelButton") as? UIButton
cancelButton?.setTitle("Done",for: .normal)
注意方法三的設(shè)置順序瘟忱,需要先設(shè)置 showsCancelButton 為 true奥额,這種方式的問(wèn)題在于 cancelButton 一開(kāi)始就要被設(shè)置為顯示。
18. 搜索框附屬分欄條
在搜索框下面可以顯示搜索框附屬分欄條访诱。 用例:
letsearchBar = searchController.searchBar
searchBar.showsScopeBar =true
// 選擇按鈕視圖的按鈕標(biāo)題
searchBar.scopeButtonTitles = ["One","Two","Three"]
// 選中的選擇按鈕下標(biāo)值垫挨,默認(rèn)值為 0,如果超出索引范圍則會(huì)被忽略
searchBar.selectedScopeButtonIndex = 1
19. 搜索框附屬分欄條——背景顏色
可以通過(guò)通過(guò)?scopeBarBackgroundImage?設(shè)置搜索框附屬分欄條的背景顏色
open var scopeBarBackgroundImage: UIImage?
用例(注意以下代碼的順序可能會(huì)產(chǎn)生不同的效果):
letsearchBar = searchController.searchBar
searchBar.showsScopeBar =true
// 選擇按鈕視圖的按鈕標(biāo)題
searchBar.scopeButtonTitles = ["One","Two","Three"]
// 選中的選擇按鈕下標(biāo)值盐数,默認(rèn)值為 0棒拂,如果超出索引范圍則會(huì)被忽略
searchBar.selectedScopeButtonIndex = 1
searchBar.scopeBarBackgroundImage = self.createImage(UIColor.yellow, size: CGSize.init(width: 200, height: 100))
20. 搜索框附屬分欄條——按鈕的背景圖片
用以下方法可以設(shè)置(獲壬√荨)搜索框附屬分欄條按鈕的背景圖片:
open funcsetScopeBarButtonBackgroundImage(_ backgroundImage: UIImage?,forstate: UIControlState)
open func scopeBarButtonBackgroundImage(forstate: UIControlState) -> UIImage?
用例:
letsearchBar = searchController.searchBar
searchBar.showsScopeBar =true
// 選擇按鈕視圖的按鈕標(biāo)題
searchBar.scopeButtonTitles = ["One","Two","Three"]
// 選中的選擇按鈕下標(biāo)值玫氢,默認(rèn)值為 0,如果超出索引范圍則會(huì)被忽略
searchBar.selectedScopeButtonIndex = 1
searchBar.scopeBarBackgroundImage = self.createImage(UIColor.yellow, size: CGSize.init(width: 200, height: 100))
searchBar.setScopeBarButtonBackgroundImage(createImage(.orange, size: CGSize.init(width: 20, height: 20)),for: .normal)
21. 搜索框附屬分欄條——按鈕的分割線圖片
可以用以下方法設(shè)置(獲让战搿)搜索框附屬分欄條按鈕的分割線圖片:
open funcsetScopeBarButtonDividerImage(_ dividerImage: UIImage?,forLeftSegmentState leftState: UIControlState, rightSegmentState rightState: UIControlState)
open func scopeBarButtonDividerImage(forLeftSegmentState leftState: UIControlState, rightSegmentState rightState: UIControlState) -> UIImage?
用例:
letsearchBar = searchController.searchBar
searchBar.showsScopeBar =true
// 選擇按鈕視圖的按鈕標(biāo)題
searchBar.scopeButtonTitles = ["One","Two","Three"]
// 選中的選擇按鈕下標(biāo)值漾峡,默認(rèn)值為 0,如果超出索引范圍則會(huì)被忽略
searchBar.selectedScopeButtonIndex = 1
searchBar.setScopeBarButtonDividerImage(createImage(.red, size: CGSize.init(width: 10, height: 20)),forLeftSegmentState: .normal, rightSegmentState: .normal)
22. 搜索框附屬分欄條——按鈕的標(biāo)題樣式
可以用以下方法設(shè)置(獲扔骺酢)搜索框附屬分欄條按鈕的標(biāo)題樣式:
open funcsetScopeBarButtonTitleTextAttributes(_ attributes: [String : Any]?,forstate: UIControlState)
open func scopeBarButtonTitleTextAttributes(forstate: UIControlState) -> [String : Any]?
用例:
letsearchBar = searchController.searchBar
searchBar.showsScopeBar =true
// 選擇按鈕視圖的按鈕標(biāo)題
searchBar.scopeButtonTitles = ["One","Two","Three"]
// 選中的選擇按鈕下標(biāo)值生逸,默認(rèn)值為 0,如果超出索引范圍則會(huì)被忽略
searchBar.selectedScopeButtonIndex = 1
searchBar.setScopeBarButtonTitleTextAttributes([NSAttributedStringKey.font.rawValue : UIFont.systemFont(ofSize: 20), NSAttributedStringKey.foregroundColor.rawValue : UIColor.red],for: .normal)
searchBar.setScopeBarButtonTitleTextAttributes([NSAttributedStringKey.font.rawValue : UIFont.systemFont(ofSize: 24), NSAttributedStringKey.foregroundColor.rawValue : UIColor.yellow],for: .selected)
23. 搜索頂部提示
在搜索框頂部可以通知 prompt 設(shè)置提示信息且预。
比如:
letsearchBar = searchController.searchBar
searchBar.prompt ="非活躍"
可以在 searchBar 的代理里修改 prompt 的內(nèi)容槽袄,例如:
extension ViewController: UISearchBarDelegate {
? ? func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.prompt ="開(kāi)始編輯"
? ? }
? ? func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.prompt ="取消編輯"
? ? }
? ? func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchBar.prompt ="當(dāng)前輸入:\(searchText)"
? ? }
? ? func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.prompt ="點(diǎn)擊取消"
? ? }
}
可以發(fā)現(xiàn)頂部的提示文字和輸入框重合了。所以向下調(diào)整一下輸入框的偏移量锋谐。 prompt 為空時(shí) searchBar 的高度為 56遍尺,不為空時(shí) searchBar 的高度為 75,所以我們將輸入框向下調(diào)整 19:
searchBar.searchFieldBackgroundPositionAdjustment = UIOffset.init(horizontal: 0, vertical: 19)
可以發(fā)現(xiàn)還是有問(wèn)題:
取消按鈕和輸入框不在一行上了
如果 prompt 有時(shí)有值涮拗,有時(shí)為空乾戏,searchBar 的高度無(wú)法靈活改變迂苛。
這些問(wèn)題暫時(shí)沒(méi)有找到解決方案。
其他待解決問(wèn)題
isTranslucent 沒(méi)有發(fā)現(xiàn)效果
inputAssistantItem
inputAccessoryView
搜索結(jié)果列表圖標(biāo)在什么條件下會(huì)顯示