Swift - 搜索条(UISearchBar)的用法
2020-06-23 本文已影响0人
小驴拉磨
1、搜索条Options属性还可设置如下功能样式:
- Shows Search Results Button:勾选后,搜索框右边显示一个圆形向下的按钮,单击会发送特殊事件。
- Shows Bookmarks Button:勾选后,搜索框右边会显示一个书本的按钮,单击会发送特殊事件。
- Shows Cancel Button:勾选后,搜索框右边会出现一个“Cancel”按钮,单击会发送特殊事件。
-
Shows Scope Bar:勾选后,会在搜索条下面出现一个分段控制器。
image.png
2、下面是一个搜索条的使用样例,功能如下:
(1)在Main.storyboard界面里拖入一个 Search Bar 和一个 Table View,Search Bar放到Table View的页眉位置
(2)初始化或者搜索条为空时,表格显示所有数据
(3)搜索条不为空时,表格实时过滤显示匹配的项目

import UIKit
class ViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
// 所有组件
var ctrls:[String] = ["长城-哈弗","宝马-6系","宝马-7系","奔驰-迈巴赫"]
// 搜索匹配的结果,Table View使用这个数组作为datasource
var ctrlsel:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
/// 设置UI
setupUI()
}
/// 设置UI
func setupUI()
{
// 起始加载全部内容
self.ctrlsel = self.ctrls
//设置代理
self.searchBar.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
// 注册TableViewCell
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
}
//MARK:UISearchBarDelegate
extension ViewController
{
// 搜索代理UISearchBarDelegate方法,每次改变搜索内容时都会调用
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
// 没有搜索内容时显示全部组件
if searchText == "" {
self.ctrlsel = self.ctrls
}
else { // 匹配用户输入内容的前缀(不区分大小写)
self.ctrlsel = []
for ctrl in self.ctrls {
if ctrl.lowercased().hasPrefix(searchText.lowercased()) {
self.ctrlsel.append(ctrl)
}
}
}
// 刷新Table View显示
self.tableView.reloadData()
}
}
//MARK:UITableViewDelegate & UITableViewDataSource
extension ViewController
{
// 返回表格行数(也就是返回控件数)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ctrlsel.count
}
// 创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
// 为了提供表格显示性能,已创建完成的单元需重复使用
let identify:String = "cell"
// 同一形式的单元格重复使用,在声明时已注册
let cell = tableView.dequeueReusableCell(withIdentifier: identify,
for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = self.ctrlsel[indexPath.row]
return cell
}
}
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_562.html