[英]UISearchbar UI in iOS 12 and 13 are different and not correct
The UI in my searchbar is behaving differently than expected.我的搜索栏中的 UI 表现与预期不同。
I want it to look like this:我希望它看起来像这样:
In iOS 13 it looks like this:在 iOS 13 中,它看起来像这样:
And in iOS 12 it looks like this:在 iOS 12 中,它看起来像这样:
I am configuring the searchbar in ViewDidLoad with this:我正在使用以下命令在 ViewDidLoad 中配置搜索栏:
guard let searchField = searchBar.value(forKey: "searchField") as? UITextField else { return }
searchBar.backgroundColor = .red
searchField.backgroundColor = UIColor.black.withAlphaComponent(0.3)
searchField.textColor = .white
searchField.leftView?.tintColor = .white
searchField.attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
I've tried to create your searchBar but I didn't test it.我已经尝试创建您的搜索栏,但我没有对其进行测试。 You can find answers to your questions from the code snippet.
您可以从代码片段中找到问题的答案。 You need to add the UISearchBar extension also to your project to use some methods in the snippet.
您还需要将UISearchBar 扩展添加到您的项目中以使用代码段中的一些方法。
searchBar.tintColor = UIColor.white
searchBar.searchBarStyle = .default
searchBar.placeholder = "Search"
searchBar.setTextFieldPlaceholderColor(color: UIColor.white)
searchBar.backgroundColor = UIColor.red
searchBar.setImage(UIImage(named:"searchIcon"), for: .search, state: .normal)
if #available(iOS 13.0, *) {
searchBar.searchTextField.backgroundColor = UIColor.black.withAlphaComponent(0.3)
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
searchBar.searchTextField.textColor = UIColor.white
searchBar.searchTextField.font = UIFont.systemFont(ofSize: 12)
} else {
searchBar.removeBackgroundImageView()
searchBar.setTextFieldBackground(color: UIColor.black.withAlphaComponent(0.3))
}
UISearchBar extension UISearchBar 扩展
extension UISearchBar {
//use for iOS 12 and below
func removeBackgroundImageView(){
if let view:UIView = self.subviews.first {
for curr in view.subviews {
guard let searchBarBackgroundClass = NSClassFromString("UISearchBarBackground") else {
return
}
if curr.isKind(of:searchBarBackgroundClass){
if let imageView = curr as? UIImageView{
imageView.removeFromSuperview()
break
}
}
}
}
}
func setTextFieldBackground(color : UIColor) {
for subView in self.subviews {
for subView1 in subView.subviews {
if subView1.isKind(of: UITextField.self) {
subView1.backgroundColor = color
(subView1 as? UITextField)?.font = UIFont.systemFont(ofSize: 12)
}
}
}
}
func setTextFieldPlaceholderColor(color : UIColor) {
for subView in self.subviews {
for subView1 in subView.subviews {
if subView1.isKind(of: UITextField.self) {
if let placeholder = (subView1 as! UITextField).placeholder {
(subView1 as! UITextField).attributedPlaceholder = NSAttributedString(string:placeholder,attributes: [NSAttributedString.Key.foregroundColor: color])
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.