更新 UISearchController 背景的正确方法是改变背景图片。
如果你在可视化调试器中看到 UISearchController 你会发现它的背景是 UIImageView:
所以你应该制作你的搜索栏的小图像并将其设置为 seachBar 像这样:
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.placeholder = "Search"
searchController.searchBar.tintColor = UIColor.black
searchController.searchBar.searchBarStyle = .minimal
// Set background image to searchBar so it will resize
searchController.searchBar.setSearchFieldBackgroundImage(UIImage(named: "oval_static"), for: .normal)
definesPresentationContext = true
return searchController
}()
searchBar的图片(项目中我推荐使用.pdf或.png格式的图片,这里只是截图):
UISearchBar 会根据需要调整它的大小,结果是:
此外,我们可以这样做以仅在代码中创建自定义背景:
/// Just random extension to make image from UIView, you can use your own
extension UIView {
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}}
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.placeholder = "Search"
searchController.searchBar.tintColor = UIColor.black
searchController.searchBar.searchBarStyle = .minimal
// Create own view with custom properties
// Default height is 36 points
let differentColorSearchBar = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 36))
differentColorSearchBar.layer.cornerRadius = 8
differentColorSearchBar.clipsToBounds = true
differentColorSearchBar.backgroundColor = UIColor.blue
searchController.searchBar.setSearchFieldBackgroundImage(differentColorSearchBar.asImage(), for: .normal)
definesPresentationContext = true
return searchController
}
结果是(当然你可以改变 searchBar 的另一个属性让它变得更好,但我只是告诉你如何正确改变背景):
我建议避免使用私有属性,只使用 open!希望有帮助。