创建一个UISearchController
如果传入的searchResultsController为nil,则表示搜索的结果在当前控制器中显示,现在我让它在searchResultVC中显示
// 创建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

设置搜索框
// 搜索框
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)
监听语音按钮的点击
// MARK:- UISearchBarDelegate
extension LXFContactViewController: UISearchBarDelegate {
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
LXFLog("点击了语音按钮")
}
}

效果

主要代码
上面仅作演示,下面的代码为searchBar的主要设置
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 高仿微信
网友评论