我使用以下代码在 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 是这样的:
如何更改搜索栏的颜色,使其与导航栏的背景颜色一致?
谢谢。
最佳答案
对于 UINavigationBar,有多种方法可以控制它的背景颜色:
- 将 tintColor 属性设置为您需要的颜色。
- 按照建议的修改方式应用自定义渐变或其他图案图像 — 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/