iOS Swift UISearchController仿微信搜索框

建立一個UISearchController

若是傳入的searchResultsController爲nil,則表示搜索的結果在當前控制器中顯示,如今我讓它在searchResultVC中顯示git

// 建立searchResultVC
let searchResultVC = UIViewController()
// 設置背景顏色爲紅色
searchResultVC.view.backgroundColor = UIColor.red
let searchController = UISearchController(searchResultsController: searchResultVC)
// 設置背景顏色
searchController.view.backgroundColor = UIColor (red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
// 默認爲YES,設置開始搜索時背景顯示與否
// searchController.dimsBackgroundDuringPresentation = false
// 默認爲YES,控制搜索時,是否隱藏導航欄
// searchController.hidesNavigationBarDuringPresentation = false

// 須要進行強引用 searchController
self.searchController = searchController

// 將搜索框視圖設置爲tableView的tableHeaderView
tableView.tableHeaderView = searchController.searchBar
複製代碼

添加searchBar

設置搜索框

// 搜索框
let bar = searchController.searchBar
// 樣式
bar.barStyle = .default
// 設置光標及取消按鈕的顏色
bar.tintColor = RGBA(r: 0.12, g: 0.74, b: 0.13, a: 1.00)
// 設置代理
bar.delegate = self
複製代碼

設置光標及取消按鈕的顏色

去除背景

// 去除背景及上下兩條橫線
bar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
複製代碼

去除背景及上下兩條橫線

添加右側語音按鈕

// 右側語音
bar.showsBookmarkButton = true
bar.setImage(#imageLiteral(resourceName: "VoiceSearchStartBtn"), for: .bookmark, state: .normal)
複製代碼

監聽語音按鈕的點擊github

// MARK:- UISearchBarDelegate
extension LXFContactViewController: UISearchBarDelegate {
    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
        LXFLog("點擊了語音按鈕")
    }
}
複製代碼

右側語音

效果

主要代碼

上面僅做演示,下面的代碼爲searchBar的主要設置swift

let commonBgColor = RGBA(r: 0.94, g: 0.94, b: 0.96, a: 1.00)
searchBar.barTintColor = commonBgColor

// 搜索框
searchBar.barStyle = .default
searchBar.tintColor = RGBA(r: 0.12, g: 0.74, b: 0.13, a: 1.00)
// 去除上下兩條橫線
searchBar.setBackgroundImage(commonBgColor.trans2Image(), for: .any, barMetrics: .default)
// 右側語音
searchBar.showsBookmarkButton = true
searchBar.setImage(#imageLiteral(resourceName: "VoiceSearchStartBtn"), for: .bookmark, state: .normal)
複製代碼
extension UIColor {
    func trans2Image() -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(self.cgColor)
        context?.fill(rect)
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return theImage ?? UIImage()
    }
}
複製代碼

附上相關項目:Swift 3.0 高仿微信微信

微信公衆號
相關文章
相關標籤/搜索