Max*_*Max 6 ios swift uisearchcontroller ios11
如何在UISearchController搜索文本字段中更改默认灰色背景?
屏幕截图

这是一个如何设置textField背景的示例.
class ViewController: UIViewController {
let searchController = UISearchController(searchResultsController: nil)
private lazy var searchTextField: UITextField? = { [unowned self] in
var textField: UITextField?
self.searchController.searchBar.subviews.forEach({ view in
view.subviews.forEach({ view in
if let view = view as? UITextField {
textField = view
}
})
})
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Candies"
navigationItem.searchController = searchController
definesPresentationContext = true
if let bg = self.searchTextField?.subviews.first {
bg.backgroundColor = .green
bg.layer.cornerRadius = 10
bg.clipsToBounds = true
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果
更新 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
}()
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
结果是(当然您可以更改 searchBar 的另一个属性以使其更好,但我只是向您展示如何正确更改背景):
我建议避免使用私有属性,只使用 open!希望它有帮助。
| 归档时间: |
|
| 查看次数: |
2948 次 |
| 最近记录: |