使UISearchBar背景清晰
我无法清除search栏我试图通过设置清晰的背景色来清除它,并且我还在search栏下放置了一个图像
我也清楚了search栏的背景
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]];
对于iOS7 +,您所需要做的只是:
[self.searchBarHome setBackgroundColor:[UIColor clearColor]]; [self.searchBarHome setBarTintColor:[UIColor clearColor]]; //this is what you want
注意 :这不适用于iOS6
对于iOS6 +,甚至在iOS7中也会照顾到它:
[self.searchBarHome setBackgroundColor:[UIColor clearColor]]; [self.searchBarHome setBackgroundImage:[UIImage new]]; [self.searchBarHome setTranslucent:YES];
UISearchBar包含两个子视图,分别是'UISearchBarBackground'和'UITextField'。 在IOS8中,你需要删除'UISearchBarBackground'来清除它。
for (UIView *subview in [[yourSearchBar.subviews lastObject] subviews]) { if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { [subview removeFromSuperview]; break; } }
移除UISearchBarBackground可能会导致未知行为,特别是当您开始以更高级的方式使用元素时。
Ruozi的答案是我首选的解决scheme来抓取UISearchBarBackground元素,但我build议将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的透明背景。
另外,为了避免混淆视图控制器,在UISearchBar子类中包含这些代码可能会更好。
设置backgroundColor和barTintColor没有工作我的iOS 9 +,留给我一个黑色的背景。 但若子解决scheme将工作。 这是一个相同代码的快速版本。
for view in _searchBar.subviews.last!.subviews { if view.isKindOfClass(NSClassFromString("UISearchBarBackground")!) { view.removeFromSuperview() } }
对于任何想要find一个非hacky解决scheme的人来说,只需在你的Storyboard / Xib文件中设置背景图像为零即可。 从字面上看,只需在UISearchBar的背景图像字段中写入nil
即可。
inheritanceuisearchbar并覆盖initWithFrame和initWithCoder方法,并将背景颜色设置为
// For searchbar created programmatically - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self configureSetup]; } return self; } // For search bar created on xib - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self configureSetup]; } return self; } - (void)configureSetup { self.backgroundColor = [UIColor clearColor]; }
并使用子类的search栏来代替你指定的UISearchBar
这是我在Swift 3(Scarafone和Andrew2M的答案组合)中的解决scheme:
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)