【问题标题】:UISearchBar clear background imageUISearchBar 清除背景图片
【发布时间】:2012-06-06 09:34:24
【问题描述】:

我的 UISearchBar 有以下代码:

 UISearchBar * searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
    searchBar.placeholder = @"Search for a tag";
    searchBar.delegate = self;

结果如下:

我想将白色背景更改为清晰的颜色。我该怎么做呢?基本上我希望 textField 背景颜色清晰

【问题讨论】:

标签: iphone objective-c ios ipad uisearchbar


【解决方案1】:

如果您支持 iOS 5 及更高版本,请执行以下操作:

[self.searchBar setBackgroundImage:[[UIImage alloc] init]];

【讨论】:

  • 太棒了——比在透明图像文件中链接要好得多。
【解决方案2】:

尝试以下代码清除背景颜色:

//to clear searchbar backgraound
- (void) clearSearchBarBg
{
    for (UIView *subview in theSearchBar.subviews) 
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
        {
            [subview removeFromSuperview];
            break;
        }
    }
}

【讨论】:

  • 不错的尝试。透明 png hack 有效:[searchBar setBackgroundImage: [UIImage imageNamed:@"bg_search.png"] ];
【解决方案3】:

制作透明图片,并在下面的代码中使用该图片。

[search setSearchFieldBackgroundImage:[UIImage imageNamed:@"bg_search.png"] forState:UIControlStateNormal];

【讨论】:

  • 我发现破坏了搜索栏文本字段而不是背景,应该是:[searchBar setBackgroundImage: [UIImage imageNamed:@"bg_search.png"] ];
【解决方案4】:

试试这个:

[[searchBar.subviews objectAtIndex:0] removeFromSuperview];

【讨论】:

    【解决方案5】:

    使用此代码:

    searchBar.backgroundColor=[UIColor clearColor];
    

    【讨论】:

      【解决方案6】:

      对于iOS 7,请使用

      [searchBar setBarTintColor:[UIColor whiteColor]];
      

      对于 ios 6,使用

      [searchBar setTintColor:[UIColor whiteColor]];
      

      【讨论】:

        【解决方案7】:

        好的,这是一个清晰的背景,“搜索”占位符是灰色的,望远镜图标也是灰色的。

        [self.searchBar setPlaceholder:@"Search          "; //the spaces push it to left align as there is no left align for the UISearchBar
        [self.searchBar setBackgroundImage:[UIImage imageNamed:@"thatSearchIconThing"] forBarPosition:UIBarPositionTop barMetrics:UIBarMetricsLandscapePhone]; //my app is landscape
        [self.search setSearchBarStyle:UISearchBarStyleMinimal];
        

        【讨论】: