如何为UISearchBar着色,使其与背景看起来无缝

时间:2012-11-22 11:17:43

标签: iphone ios uisearchbar uisearchdisplaycontroller

我正在尝试为这个UISearchBar着色,使其看起来与背景无缝(如第二张图片中所示)。是否有可能做到这一点?我已尝试在IB中进行编程,但没有运气。

感谢您的帮助

UISearchBar screenshot

这是理想的外观:

UISearchBar screenshot - desired look

2 个答案:

答案 0 :(得分:2)

   UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
    [searchField setBackground:[UIImage imageNamed:@"searchfield_bg"]];

    [self.searchBar setTintColor:[UIColor blackColor]];
    UIImage *searchimg = [UIImage imageNamed:@"search_panel.png"];

    for (UIView *subview in self.searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor colorWithPatternImage:searchimg];
            [self.searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            [bg release];
            break;
        }
    }

我使用这些图片,您可以使用并更改颜色,我的要求是制作黑色搜索栏,所以我使用黑色

enter image description here enter image description here

它看起来像: enter image description here

答案 1 :(得分:1)

就像这样的setTint颜色..

    [searchBar setBarStyle:UIBarStyleDefault];
    [searchBar setTintColor:[UIColor colorWithRed:.81 green:.14 blue:.19 alpha:1]];//set alpha with your requirement 

还有图像使用这个代码它的工作很棒..

   for (UIView *subview in searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top-bar.png"]];
            [searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            break;
        }
    }

对于整个红色搜索栏,然后简单的复制粘贴这个代码配对..在这里我解决了这个问题

    for (UIView *subview in searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor redColor];
            [searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            break;
        }
    }
    [searchBar setTintColor:[UIColor redColor]];