14

我目前正在开发一个在 ios7 出现之前运行良好的应用程序。搜索栏过去是透明的,并与导航栏的蓝色背景融为一体。现在我在 ios7 中工作,导航栏是蓝色的,但是搜索栏的背景是灰色的。如何使它变成蓝色或透明?

这是一张图片:

在此处输入图像描述

4

5 回答 5

36

尝试这个:

if(IOS_7)
{
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
}
于 2013-10-04T04:20:08.847 回答
12

您可以在 Interface Builder (.xib) 中将“Bar Tint”设置为“Clear Color”:

在此处输入图像描述

也可以在代码中完成:

self.searchBar.barTintColor = [UIColor clearColor];
于 2013-10-03T22:21:26.163 回答
6

要使其成为纯色,您只需删除 UISearchBarBackground 视图。

我创建了一个递归方法来正确清理搜索栏。

- (void) removeUISearchBarBackgroundInViewHierarchy:(UIView *)view
{
    for (UIView *subview in [view subviews]) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [subview removeFromSuperview];
            break; //To avoid an extra loop as there is only one UISearchBarBackground
        } else {
            [self removeUISearchBarBackgroundInViewHierarchy:subview];
        }
    }
}

您可以简单地将搜索栏发送到该方法,然后更改颜色。

[self removeUISearchBarBackgroundInViewHierarchy:self.searchDisplayController.searchBar];
self.searchDisplayController.searchBar.backgroundColor = yourUIColor;
于 2014-03-13T14:23:32.373 回答
0

斯威夫特 4.2

您可以使用此扩展来更改 SearchBar 的字体和背景颜色。

extension UISearchBar {

    var textField: UITextField? {
        let subViews = subviews.flatMap { $0.subviews }
        guard let tf = (subViews.filter { $0 is UITextField }).first as? UITextField else { return nil }
        return tf
    }

    func setTextColor(color: UIColor) {
         textField?.textColor = color
    }

    func setBackgroundColor(color: UIColor) {
         textField?.backgroundColor = color
    }
}
于 2018-11-27T22:59:38.607 回答
-1

**编辑 - 这在 iOS 7 中对我有用

// Set the color to whatever blue color that is in your screenshot
self.searchBar.backgroundImage = [UIImage imageWithColor:[UIColor redColor] cornerRadius:5.0f];

如果您希望所有搜索栏都具有某种颜色,请执行以下操作:

// Put this in your app delegate's didFinishLaunchingWithOptions method
// Whatever color you want for searchBarColor
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) { // For iOS 7
    UIColor *searchBarColor = [UIColor blueColor];
    [[UISearchBar appearance] setBackgroundColor:searchBarColor];
}

如果您只想让特定的搜索栏背景成为一种颜色:

// Set it in your viewDidLoad method of your controller
// Replace the yourSearchBar property with whatever you're doing to instantiate the search bar
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) { // For iOS 7
{
    UIColor *searchBarColor = [UIColor blueColor];
    self.yourSearchBar.backgroundColor = searchBarColor;
}
于 2013-10-03T21:46:20.313 回答