无法将UISearchBar的translucent属性设置为NO。

4

我正在尝试设置UISearchBarbarTintColor,但不想让它透明。然而,设置translucent属性似乎没有任何作用。我已经在这里的Xcode项目中复制了这个问题。

self.searchDisplayController.searchBar.translucent = NO;
self.searchDisplayController.searchBar.barTintColor = [UIColor redColor];

上面的红色并不同于在不透明的UIViews中使用[UIColor redColor]。我知道有一种解决方法是在搜索栏上设置背景图片,但是以上代码也应该可以工作。
3个回答

4

我下载了你的代码并找到解决方案,添加了一个名为removeUISearchBarBackgroundInViewHierarchy的方法,并将searchBar.backgroundColor设置为redColor

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.searchDisplayController.searchBar.translucent = NO;

    [self removeUISearchBarBackgroundInViewHierarchy:self.searchDisplayController.searchBar];
    self.searchDisplayController.searchBar.backgroundColor = [UIColor redColor];
}

- (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];
        }
    }
}

1
这是一种超级hacky的方法,但我确认它有效。 - Jamie Forrest
我在等待看看是否有其他人提出了不涉及删除私有子视图的解决方案。 - Jamie Forrest
功能很好,但遗憾的是,当搜索栏聚焦时,状态栏背景会变成透明的,而不是原来的UISearchBarBackground颜色。 - Skoua

0
请在搜索栏中设置图像,这样可以解决您的问题。
[[UISearchBar appearance] setBackgroundImage:[UIImage imageNamed:@"red"]];

谢谢。


1
我正在尝试通过 barTintColor 来实现,而不是设置背景图片。 - Jamie Forrest
是的,但我有同样的问题,我无法使用barTintColor获取我想要显示的相同颜色,这就是为什么我应用了上述逻辑来获得精确结果的原因。 - Banker Mittal

0

或许已经晚了一步,

但是我为Swift 3开发了一个非常简单而实用的扩展,可以让你轻松使用半透明属性。

它不涉及任何私有API或对象内部的危险操作。

你可以从这个Github代码库下载它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接