iOS7,UISearchBar的背景图像

25

我正在将UI从iOS 6过渡到iOS 7。

我们有一个与UISearchDisplayController相关的UISearchBar,我已经将navigationBar和searchBar的backgroundImage设置为使用颜色动态创建的1x1图像。

self.searchDisplayController.searchBar.translucent = NO;
self.searchDisplayController.searchBar.barTintColor = [UIColor clearColor];
self.searchDisplayController.searchBar.tintColor = [UIColor myTintColor];
self.searchDisplayController.searchBar.backgroundImage = [self imageWithColor:[UIColor myBGColor]];
self.searchDisplayController.searchBar.scopeBarBackgroundImage = [self imageWithColor:[UIColor myBGColor]];
在iOS6上,一切都按预期工作。 在iOS7上,当选择searchBar时,scopeBar会显示出良好的背景图片(使用searchBar.scopeBarBackgroundImage设置),但是searchBar会变成半透明灰色。当我点击“取消”时,searchBar的背景图像会恢复。

How it looks

/////////////////////////////////////////////////////////////////////////////////////////////////////

修改后的问题

/////////////////////////////////////////////////////////////////////////////////////////////////////

实际上,我在这里和那里使用了barTintColor和其他选项,但它们不起作用。下面是将barTintColor设置为相同颜色的结果。但是顶部有一个白色层。 enter image description here

4个回答

41

iOS 7中,属性backgroundImagescopeBarBackgroundImage不再按预期工作并变为半透明。

iOS 7引入了以下方法来解决这个问题。(文档在这里)

setBackgroundImage:forBarPosition:barMetrics:

以下是您应该做的:

 [self.searchDisplayController.searchBar setBackgroundImage:[self imageWithColor:[UIColor yourColor]] 
                                             forBarPosition:0 
                                                 barMetrics:UIBarMetricsDefault];

这里的barPosition : 0 是指 UIBarPositionAny

编辑:

Swift 代码:

self.searchDisplayController.searchBar.setBackgroundImage(self.image(color: UIColor.yourColor), for: UIBarPosition(rawValue: 0)!, barMetrics:.default)

1
感谢您的帮助,但很遗憾它还是没有改变! - Geraud.ch
1
请查看已编辑的答案并告诉我它是否有效! - aksh1t
你做到了!非常感谢!! - Geraud.ch
1
是的,非常感谢aksh1t,这非常有帮助! - Karan Patel
我已经寻找了很久,这个答案帮了我很多! - alexzg
花了半天时间——你真的节省了我的时间! - hbk

4

我能够复制您想要做的事情,并且如果我将barTintColor设置为我的颜色选择,它似乎对我有用。

我建议尝试以下操作:

self.searchDisplayController.searchBar.barTintColor = [UIColor myBGColor];

我使用了[UIColor redColor],得到了我期望的结果。


我编辑了我的问题,并附上了结果的截图。这不是我期望的,你得到了相同的结果吗? - Geraud.ch
如果您已将 translucent 设置为 NO,则它不应该执行您所展示的操作。看起来您正在使用图像作为颜色,您是否尝试过只使用纯色,例如 [UIColor blueColor] - Mike Z

0
如果您设置搜索栏的barTintColor属性,您将得到您期望的效果。我刚刚尝试了一下,它可以正常工作:
self.searchDisplayController.searchBar.barTintColor = [UIColor yellowColor];

请注意,barTintColor属性是在iOS 7中引入的。

谢谢你的帮助。我编辑了我的问题,并附上了结果的截图。这不是我期望的,你得到了相同的结果吗? - Geraud.ch
没有白色的层,它看起来是这样的,因为它是半透明的。尝试这个“self.searchDisplayController.searchBar.translucent = NO;” - amb
很不幸,这已经是事实。看起来这个搜索栏出了问题。 - Geraud.ch
我也遇到了同样的问题。UISearchBar 似乎不会遵守其 translucent 属性。 - Jamie Forrest

0

由于目前没有 Swift 版本,我将把这个留下来以供未来使用,因为我也一直在为此苦苦挣扎。

  1. 获得所需颜色的 1px 图像(甚至可以是透明的)

  2. 使用以下代码将其设置为背景图像:

    searchController.searchBar.setBackgroundImage(UIImage(named: "red"), for: .any, barMetrics: .default)


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