标签:
UISearchBar是一个搜索栏,继承自UIView,也是常用的控件之一,所以特别写一篇备忘方便以后做工具文章。
let searchBar = UISearchBar(frame: CGRectMake(0, 64, view.frame.size.width, 40))
searchBar.barStyle = .Default
searchBar.placeholder = "请输入一些内容"
searchBar.showsCancelButton = true
searchBar.showsSearchResultsButton = true
searchBar.tintColor = UIColor.orangeColor()
searchBar.showsScopeBar = true
searchBar.scopeButtonTitles = ["分组1", "分组2"]
searchBar.selectedScopeButtonIndex = 1
searchBar.delegate = self
view.addSubview(searchBar)
一些常用的属性方法(更多请参考官方文档):
// 是否应该开始编辑
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
return true
}
// 搜索栏开始编辑的回调
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
print("begin editing")
}
// 是否应该结束编辑
func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
return true
}
// 搜索栏结束编辑的回调
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
print("end editing")
}
// 当搜索栏内的文字发生变化时调用,返回是否允许改变。
func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
print("\(range), \(text)")
return true
}
// 取消按钮点击事件
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
print("cancel button click")
searchBar.text = nil
searchBar.resignFirstResponder()
}
// 点击了搜索按钮的回调
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
print("search button click")
searchBar.resignFirstResponder()
}
// 搜索结果列表按钮被点击
func searchBarResultsListButtonClicked(searchBar: UISearchBar) {
print("results list click")
}
// 当搜索栏的内容已经发生变化时调用
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
}
// 点击了附加视图按钮后调用
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
print(selectedScope)
}
标签:
原文地址:http://www.cnblogs.com/Alex-sk/p/5578619.html