Change UISearchBar background image in iOS11

拥有回忆 提交于 2019-12-23 20:51:47

问题


I want to change my UISearchBar background image. When adding it as the header view in my UITableView it works perfectly fine. However, when I want to change it for the SearchBar being set as the searchController of the navigationItem it won´t change the background image.

I´m using:

self.searchBar.searchBar.setBackgroundImage(UIImage(named: "#IMAGENAME")?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .any, barMetrics: UIBarMetrics.default)

Does anybody know how to fix this issue?


回答1:


You may be looking for this:

if #available(iOS 11.0, *) {
    let sc = UISearchController(searchResultsController: nil)
    if let navigationbar = self.navigationController?.navigationBar {
        navigationbar.barTintColor = UIColor(patternImage: UIImage(named: "pattern")!)
    }
    navigationItem.searchController = sc
    navigationItem.hidesSearchBarWhenScrolling = false
}

Here is image:

And here is result:

Here is more detailed answer, if you want to change any other UI elements of search bar.

  • iOS 11 UISearchBar in UINavigationBar



回答2:


Use the below Code I have used the similar One :

// Objective-c Code

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

// Swift Code

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

Please let me know the result



来源:https://stackoverflow.com/questions/48203253/change-uisearchbar-background-image-in-ios11

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