iOS7, backgroundImage for UISearchBar

空扰寡人 提交于 2019-11-30 02:02:18

In iOS 7, the properties backgroundImage and scopeBarBackgroundImage no longer work as expected and become translucent.

The following method has been introduced in iOS 7 which addresses this problem. (Docs here)

setBackgroundImage:forBarPosition:barMetrics:

Here's what you should do :

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

Here, barPosition : 0 is UIBarPositionAny.

Edit:

Swift code:

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

I was able to replicate what you were trying to do and it seems to work for me if I set the barTintColor to my color choice.

I'd suggest trying:

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

I did [UIColor redColor] and got the results I expected.

If you set the barTintColor property of your search bar, you will get what you are expecting. I've just tried this and it works:

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

Keep in mind that barTintColor property was introduced in iOS 7.

Since there is no current Swift version, I'll just leave this here for future use, as I have been struggling with it for pretty long time as well.

  1. get yourself 1px image with desired color (even clear)

  2. set it as a backgroundImage using:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!