我无法清除搜索栏,我试图通过将其背景颜色设置为透明来使其变得清晰,并且我也将一幅图像放置在搜索栏下
我也已经明确了搜索栏的背景
for (UIView *subview in self.searchBarHome.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];//please help me to make clear background of uisearchbar
break;
}
}
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBarTintColor:[UIColor clearColor]]; //this is what you want
NOTE:这不适用于iOS6
对于iOS6 +,即使在iOS7中也将由以下人员处理:
[self.searchBarHome setBackgroundColor:[UIColor clearColor]]; [self.searchBarHome setBackgroundImage:[UIImage new]]; [self.searchBarHome setTranslucent:YES];
extension UISearchBar {
func changeSearchBarColor(fieldColor: UIColor, backColor: UIColor, borderColor: UIColor?) {
UIGraphicsBeginImageContext(bounds.size)
backColor.setFill()
UIBezierPath(rect: bounds).fill()
setBackgroundImage(UIGraphicsGetImageFromCurrentImageContext()!, for: UIBarPosition.any, barMetrics: .default)
let newBounds = bounds.insetBy(dx: 0, dy: 8)
fieldColor.setFill()
let path = UIBezierPath(roundedRect: newBounds, cornerRadius: newBounds.height / 2)
if let borderColor = borderColor {
borderColor.setStroke()
path.lineWidth = 1 / UIScreen.main.scale
path.stroke()
}
path.fill()
setSearchFieldBackgroundImage(UIGraphicsGetImageFromCurrentImageContext()!, for: UIControlState.normal)
UIGraphicsEndImageContext()
}
}
searchBar.searchBarStyle = .minimal
对我有用。 for view in searchBar.subviews.last!.subviews {
if type(of: view) == NSClassFromString("UISearchBarBackground"){
view.alpha = 0.0
}
}
或替代:
searchBar.barTintColor = UIColor.clear searchBar.backgroundColor = UIColor.clear searchBar.isTranslucent = true searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
for (UIView *subview in [[yourSearchBar.subviews lastObject] subviews]) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];
break;
}
}
Ruozi的答案是获取UISearchBarBackground元素的首选方法,但是我建议将alpha设置为0,而不是使用以下方法删除视图:
for (UIView *subview in [[self.searchBar.subviews lastObject] subviews]) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview setAlpha:0.0];
break;
}
}
将以上代码添加到包含IBOutlet * searchBar的UIViewController子类中。此代码段将为iOS8和iOS9提供透明的背景。此外,为了避免使viewController混乱,在UISearchBar子类中包含此代码可能是更好的设计决策。
nil
。Swift 4.1 | iOS 11.4
NOT