Unable to set translucent UISearchBar property to NO

I am trying to set barTintColorfor UISearchBarwithout transparency. However, setting the property translucentdoes not seem to do anything. I reproduced the problem in the bare-bones Xcode project here .

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

The red color above does not match [UIColor redColor]in UIViews, which is not translucent. I know of a workaround with setting the background image in the search bar, but the code above should work too.

+4
source share
3 answers

I downloaded your code and found a solution for, add one method name removeUISearchBarBackgroundInViewHierarchyand set searchBar.backgroundColorasredColor.

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

, , .

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

.

0

Maybe it's too late for the party

However, I made a very simple and excellent extension for Swift 3, which allows you to easily use the transparent property.

It does not use a private API or a dangerous passage inside an object.

You can download it from the Github repository .

0
source

Source: https://habr.com/ru/post/1539851/


All Articles