UISearchBar的使用
import UIKit
class ViewController: UIViewController {
var searchBar: UISearchBar?
override func viewDidLoad() {
super.viewDidLoad()
self.setupSearchBar()
}
func setupSearchBar() {
self.searchBar = UISearchBar(frame: CGRect(x: 20, y: 64+10, width: UIScreen.main.bounds.width-2*20, height: 50))
self.searchBar?.placeholder = "热门话题"
/**
public enum UISearchBarStyle : UInt {
case `default` // currently UISearchBarStyleProminent 有背景 默认样式
case prominent // used my Mail, Messages and Contacts 有背景 突出样式
case minimal // used by Calendar, Notes and Music 无背景 最小样式
}
*/
self.searchBar?.searchBarStyle = .minimal
/**
public enum UIBarStyle : Int {
case `default` 白色
case black 黑色
public static var blackOpaque: UIBarStyle { get } // Deprecated. Use UIBarStyleBlack 黑色
case blackTranslucent // Deprecated. Use UIBarStyleBlack and set the translucent property to YES 黑色
}
*/
// 设置样式
self.searchBar?.barStyle = .default
// 设置背景色
self.searchBar?.barTintColor = UIColor.red
// 点击return自动搜索
self.searchBar?.enablesReturnKeyAutomatically = true
/**
public enum UISearchBarIcon : Int {
case search // The magnifying glass
case clear // The circle with an x in it
case bookmark // The open book icon
case resultsList // The list lozenge icon
}
*/
// _的作用:忽略返回值,消除警告
_ = self.searchBar?.image(for: .resultsList, state: .highlighted)
self.searchBar?.delegate = self
self.view.addSubview(self.searchBar!)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.searchBar?.resignFirstResponder()
}
}
// MARK: 搜索代理UISearchBarDelegate方法
extension ViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
print("将要开始编辑")
return true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
print("已经开始编辑")
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
print("将要结束编辑")
return true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
print("已经结束编辑")
}
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print("文本改变的时候触发 text: \(text)")
return true
}
}