【问题标题】:Cannot set UISearchBar's translucent property to NO无法将 UISearchBar 的半透明属性设置为 NO
【发布时间】:2014-06-26 16:42:57
【问题描述】:

我正在尝试将 barTintColorUISearchBar 设置为不透明。但是,设置 translucent 属性似乎没有任何作用。我已经在bare-bones Xcode project here 中重现了这个问题。

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

上面的红色和UIViews中的[UIColor redColor]不一样,不是半透明的。我知道涉及在搜索栏上设置背景图像的解决方法,但上面的代码应该也可以。

【问题讨论】:

    标签: ios objective-c ios7 uisearchbar bartintcolor


    【解决方案1】:

    我下载了您的代码并找到了解决方案,添加一个方法名称为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];
            }
        }
    }
    

    【讨论】:

    • 这是一种超级 hacky 的方法,但我确认它有效。
    • 我在等着看看有没有人想出不涉及删除私有子视图的东西。
    • 效果很好,但遗憾的是,当 searchBar 获得焦点时,状态栏背景变为透明,而不是原来的 UISearchBarBackground 颜色。
    【解决方案2】:

    请像这样在搜索栏中设置图片,它将解决您的问题。

    [[UISearchBar appearance] setBackgroundImage:[UIImage imageNamed:@"red"]];
    

    谢谢。

    【讨论】:

    • 我正在尝试通过barTintColor 来实现,而不是通过设置背景图片。
    • 是的,但我有同样的问题,我无法使用 barTintColor 获得想要显示的相同颜色,这就是为什么应用上述逻辑来获得确切结果的原因。
    【解决方案3】:

    派对可能为时已晚,

    不过,我已经为 Swift 3 做了一个非常简单和漂亮的扩展,它允许您使用 translucent 属性而没有任何麻烦。

    它不涉及在对象内使用私有 API 或危险的遍历。

    你可以从这个Github repository下载它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多