iOS 搜索栏控件 UISearchBar
1. UISearchBar 使用
let searchBar = UISearchBar(frame: CGRect(x: 15, y: 1400, width: 350, height: 150))
searchBar.searchBarStyle = UISearchBar.Style.minimal
searchBar.placeholder = "请输入关键字"
searchBar.prompt = "搜索框控件标题"
searchBar.showsCancelButton = true
searchBar.showsBookmarkButton = true
searchBar.showsSearchResultsButton = false
searchBar.showsScopeBar = true
searchBar.scopeButtonTitles = ["综合", "销量", "价格", "筛选"]
searchBar.selectedScopeButtonIndex = 1
searchBar.delegate = self
scrollView.addSubview(searchBar)
效果展示:
2. UISearchBarDelegate 协议详解
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
print("searchBarShouldBeginEditing")
return true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
print("searchBarTextDidBeginEditing")
}
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)")
}
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)")
}
日志打印:
附 Github 源码:
ViewController.swift
|