1胁艰,搜索條Options屬性還可設(shè)置如下功能樣式:
Shows Search Results Button:勾選后,搜索框右邊顯示一個(gè)圓形向下的按鈕,單擊會(huì)發(fā)送特殊事件腾么。
Shows Bookmarks Button:勾選后奈梳,搜索框右邊會(huì)顯示一個(gè)書本的按鈕,單擊會(huì)發(fā)送特殊事件解虱。
Shows Cancel Button:勾選后攘须,搜索框右邊會(huì)出現(xiàn)一個(gè)“Cancel”按鈕,單擊會(huì)發(fā)送特殊事件殴泰。
Shows Scope Bar:勾選后于宙,會(huì)在搜索條下面出現(xiàn)一個(gè)分段控制器。
2悍汛,下面是一個(gè)搜索條的使用樣例捞魁,功能如下:
(1)在Main.storyboard界面里拖入一個(gè) Search Bar 和一個(gè) Table View,Search Bar放到Table View的頁眉位置
(2)初始化或者搜索條為空時(shí)离咐,表格顯示所有數(shù)據(jù)
(3)搜索條不為空時(shí)谱俭,表格實(shí)時(shí)過濾顯示匹配的項(xiàng)目
import UIKit
class ViewController: UIViewController,UISearchBarDelegate,
UITableViewDataSource,UITableViewDelegate {
// 引用通過storyboard創(chuàng)建的控件
@IBOutlet var searchBar : UISearchBar!
@IBOutlet var tableView : UITableView!
// 所有組件
var ctrls:[String] = ["Label","Button1","Button2","Switch"]
// 搜索匹配的結(jié)果,Table View使用這個(gè)數(shù)組作為datasource
var ctrlsel:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
// 起始加載全部內(nèi)容
self.ctrlsel = self.ctrls
//設(shè)置代理
self.searchBar.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
// 注冊(cè)TableViewCell
self.tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "SwiftCell")
}
// 返回表格行數(shù)(也就是返回控件數(shù))
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ctrlsel.count
}
// 創(chuàng)建各單元顯示內(nèi)容(創(chuàng)建參數(shù)indexPath指定的單元)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
// 為了提供表格顯示性能宵蛀,已創(chuàng)建完成的單元需重復(fù)使用
let identify:String = "SwiftCell"
// 同一形式的單元格重復(fù)使用昆著,在聲明時(shí)已注冊(cè)
let cell = tableView.dequeueReusableCellWithIdentifier(identify,
forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = self.ctrlsel[indexPath.row]
return cell
}
// 搜索代理UISearchBarDelegate方法,每次改變搜索內(nèi)容時(shí)都會(huì)調(diào)用
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
// 沒有搜索內(nèi)容時(shí)顯示全部組件
if searchText == "" {
self.ctrlsel = self.ctrls
}
else { // 匹配用戶輸入內(nèi)容的前綴(不區(qū)分大小寫)
self.ctrlsel = []
for ctrl in self.ctrls {
if ctrl.lowercaseString.hasPrefix(searchText.lowercaseString) {
self.ctrlsel.append(ctrl)
}
}
}
// 刷新Table View顯示
self.tableView.reloadData()
}
// 搜索代理UISearchBarDelegate方法术陶,點(diǎn)擊虛擬鍵盤上的Search按鈕時(shí)觸發(fā)
/**func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}**/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}