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("已經(jīng)開始編輯")
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
print("將要結(jié)束編輯")
return true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
print("已經(jīng)結(jié)束編輯")
}
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print("文本改變的時候觸發(fā) text: \(text)")
return true
}
}