iphone - UINavigationItem 中的 SearchBar

标签 iphone ios uinavigationcontroller uisearchbar uinavigationitem

我使用以下代码在 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 是这样的:

enter image description here

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

谢谢。

最佳答案

对于 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

关于iphone - UINavigationItem 中的 SearchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990950/

相关文章:

iphone - startMonitoringSignificantLocationChanges 的替代方案?

iphone - 如何让 UITextView 仅在充满文本时滚动

css - HTML 电子邮件中 ​​div 的 100% 宽度样式在 iPhone 上不起作用

iphone - iOS 上的 Safari 'Top Sites' 样式

ios - 如何向 iOS 添加导航 Controller /栏?

ios - 在这种情况下我应该使用导航 Controller 吗?

iphone - "_KUTTypeMovie_"引用自 : Error in xcode

objective-c - 设计决策 : Loading an NSArray up front vs. 询问代表特定项目

ios - 确定使用 Crashlytics 记录的 "EXC_BAD_ACCESS KERN_INVALID_ADDRESS"的根本原因

ios - 如何在按下导航后退按钮和某些点击事件时加载插页式广告?