【问题标题】:SearchBar in UINavigationItemUINavigationItem 中的搜索栏
【发布时间】:2011-08-09 03:01:22
【问题描述】:

我使用以下代码在 UINavigationItem 中添加了一个搜索栏:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[searchBar sizeToFit];
searchBar.delegate = self;
self.navigationItem.titleView = searchBar;
self.navigationItem.title = self.category.title;
[searchBar release];

但结果 UI 是这样的:

如何更改搜索栏的颜色,使其与导航栏的背景相同?

谢谢。

【问题讨论】:

    标签: iphone ios uinavigationcontroller uisearchbar uinavigationitem


    【解决方案1】:

    对于 UINavigationBar,有多种方法可以控制它的背景颜色:

    1. 将 tintColor 属性设置为您需要的颜色。
    2. 按照建议的修改方式应用自定义渐变或其他图案图像 — http://leonov.co/2011/04/uinavigationbar-and-uitoolbar-customization-ultimate-solution/

    对于搜索栏 tintColor 也可用。但在你的情况下,我建议继承表单 UISearchBar 并提供如下所示的实现,以完全摆脱背景绘图例程。在这种情况下,您将在透明工具栏上获得搜索栏,并且您将只需要管理 UINavigationBar 颜色。

    //TransparentSearchBar.m
    
    @interface TransparentSearchBar()
    - (void)removeBackgroundView;
    @end
    
    @implementation TransparentSearchBar
    
    - (id)init
    {
        self = [super init];
    
        if(self) {
            [self removeBackgroundView];
        }
    
        return self;
    }
    
    - (id)initWithCoder:(NSCoder *)aDecoder 
    {
        self = [super initWithCoder:aDecoder];
    
        if(self) {
            [self removeBackgroundView];
        }
    
        return self;
    }
    
    - (id)initWithFrame:(CGRect)frame 
    {
        self = [super initWithFrame:frame];
    
        if(self) {
            [self removeBackgroundView];
        }
    
        return self;
    }
    
    - (void)removeBackgroundView 
    {
        for (UIView *view in self.subviews)
        {
            if ([view isKindOfClass:NSClassFromString
                 (@"UISearchBarBackground")])
            {
                [view removeFromSuperview];
                break;
            }
        }
    }
    
    @end
    

    【讨论】:

    • 我从 UISearchBar 继承,drawRect 设置为空,然后在我的代码中使用该类。但搜索栏不透明。我不想改变导航栏的颜色,我只想让搜索栏透明,这样看起来更好。这似乎是解决方案,但它不起作用。
    • 我的错。我用 UIToolbar 模拟了它,但这没有用。我为 UISearchBar 编写了一个替代解决方案,您可以在我的答案中找到它。
    • 嗨,Nikita,您的解决方案在 iOS 4.3 上运行良好。但是当我最近在 4.1 iPhone 上运行该应用程序时,搜索栏的背景是黑色的。你对此有什么想法吗?谢谢。
    • self.backgroundColor = [UIColor clearColor]; 也必须添加到 removeBackgroundView 中。它删除了重绘条时出现的黑色背景。可能它可以帮助 4.1,虽然我没有检查。
    【解决方案2】:

    如果您在 UISearchBar 上看到文档,它具有“tintColor”属性。 将其设置为导航栏的颜色。

    如果不知道navigationbar的颜色,获取navigationBar的tintColor。

    您可能还想使用搜索栏的“半透明”属性。可能会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2016-09-15
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多