如何清除 iOS10 Swift 中的 UISearchBar 背景颜色?
How to clear UISearchBar background color in iOS10 Swift?
由于 UISearchBar 中的布局更改,旧版本的 iOS 不再适用此问题的旧版本。
我尝试了以下方法来完全删除 UISearchBar 的背景色,但它不起作用。 (我试图查找它的层次结构视图,但 xCode 一直因为这个选项而崩溃。)
private func clearBackgroundColor() {
for view in self.subviews {
view.backgroundColor = UIColor.clear
for subview in view.subviews {
subview.backgroundColor = UIColor.clear
}
}
}
有什么想法或建议吗?
谢谢!!
我想你提到了搜索栏的 BarTintColor
试试这个:
searchBar.barTintColor = .white
试试这个。
class CustomSearchBar: UISearchBar {
override func layoutSubviews() {
super.layoutSubviews()
clearBackgroundColor() // function in the question
}
}
private func clearBackgroundColor() {
for view in self.subviews {
view.backgroundColor = UIColor.clear
for subview in view.subviews {
subview.backgroundColor = UIColor.clear
}
}
}
private func clearBackgroundColor() {
guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }
for view in self.subviews {
for subview in view.subviews where subview.isKind(of: UISearchBarBackground) {
subview.alpha = 0
}
}
}
这就是我最终所做的工作。谢谢大家的回答。
尝试设置背景图片:
[searchBar setBackgroundImage:[UIImage new]];
只需在 Interface Builder 或代码中将搜索栏样式设置为 .Minimal
,背景就会变为透明。
let searchBar = UISearchBar()
searchBar.backgroundImage = UIImage()
您可以在 Interface Builder 中将搜索样式更改为“最小”
由于 UISearchBar 中的布局更改,旧版本的 iOS 不再适用此问题的旧版本。
我尝试了以下方法来完全删除 UISearchBar 的背景色,但它不起作用。 (我试图查找它的层次结构视图,但 xCode 一直因为这个选项而崩溃。)
private func clearBackgroundColor() {
for view in self.subviews {
view.backgroundColor = UIColor.clear
for subview in view.subviews {
subview.backgroundColor = UIColor.clear
}
}
}
有什么想法或建议吗?
谢谢!!
我想你提到了搜索栏的 BarTintColor
试试这个:
searchBar.barTintColor = .white
试试这个。
class CustomSearchBar: UISearchBar {
override func layoutSubviews() {
super.layoutSubviews()
clearBackgroundColor() // function in the question
}
}
private func clearBackgroundColor() {
for view in self.subviews {
view.backgroundColor = UIColor.clear
for subview in view.subviews {
subview.backgroundColor = UIColor.clear
}
}
}
private func clearBackgroundColor() {
guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }
for view in self.subviews {
for subview in view.subviews where subview.isKind(of: UISearchBarBackground) {
subview.alpha = 0
}
}
}
这就是我最终所做的工作。谢谢大家的回答。
尝试设置背景图片:
[searchBar setBackgroundImage:[UIImage new]];
只需在 Interface Builder 或代码中将搜索栏样式设置为 .Minimal
,背景就会变为透明。
let searchBar = UISearchBar()
searchBar.backgroundImage = UIImage()
您可以在 Interface Builder 中将搜索样式更改为“最小”