// 创建 UISearchBar
let searchBar = UISearchBar(frame: CGRect(x: 15, y: 1400, width: 350, height: 150))
// 设置 UISearchBar 风格
searchBar.searchBarStyle = UISearchBar.Style.minimal // 极简风格
// 设置 UISearchBar 风格颜色
// searchBar.barTintColor = UIColor.cyan
// 设置 UISearchBar 背景图片
// searchBar.backgroundImage = UIImage(named: "demo")
// 设置 UISearchBar 提示文字
searchBar.placeholder = "请输入关键字"
// 设置 UISearchBar 标题
searchBar.prompt = "搜索框控件标题"
// 显示 UISearchBar 右侧取消按钮
searchBar.showsCancelButton = true
// 显示 UISearchBar 书库按钮
searchBar.showsBookmarkButton = true
// 显示 UISearchBar 搜索结果按钮
searchBar.showsSearchResultsButton = false
// 设置 UISearchBar 显示附件视图
searchBar.showsScopeBar = true
// 设置 UISearchBar 附件视图的标题
searchBar.scopeButtonTitles = ["综合", "销量", "价格", "筛选"]
// 设置 UISearchBar 附件视图默认选中的索引
searchBar.selectedScopeButtonIndex = 1
// 设置协议
searchBar.delegate = self
scrollView.addSubview(searchBar)
效果展示:
2. UISearchBarDelegate 协议详解
// 搜索栏将要开始编辑时回调,返回 true 允许进入编辑态,否则不允许
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
print("searchBarShouldBeginEditing")
return true
}
// 搜索栏已经开始编辑时回调
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
print("searchBarTextDidBeginEditing")
}
// 搜索栏将要结束编辑时回调,返回 true 允许结束编辑态,否则不允许
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
print("searchBarShouldEndEditing")
return true
}
// 搜索栏已经结束编辑时回调
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
print("searchBarTextDidEndEditing")
}
// 搜索栏的文本发生变化时回调。非常重要
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("searchBar, searchText: \(searchText)")
}
// 搜索栏的文本将要发生变化时回调,返回 false 则此次修改无效
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print("searchBar, replacementText: \(text)")
return true
}
// 点击键盘上的搜索按钮时回调
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("searchBarSearchButtonClicked")
}
// 点击搜索栏的书库按钮时回调
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
print("searchBarBookmarkButtonClicked")
}
// 点击搜索栏的取消按钮时回调
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
print("searchBarCancelButtonClicked")
}
// 点击搜索栏的搜索结果按钮时回调
func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
print("searchBarResultsListButtonClicked")
}
// 点击搜索栏的附件视图上的选项按钮时回调
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
print("searchBar, selectedScopeButtonIndexDidChange: \(selectedScope)")
}
日志打印:
ViewController.swift
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)