How to change SearchBar border color

时光总嘲笑我的痴心妄想 提交于 2019-12-03 22:12:50

self.searchBar.searchBar.searchBarStyle = UISearchBarStyle.Prominent
self.searchBar.searchBar.translucent = false
let textFieldInsideSearchBar = self.searchBar.searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.backgroundColor = UIColor.whiteColor()
self.searchBar.searchBar.barTintColor = UIColor.whiteColor()

Code above will give you all white searchbar but likely there will be black lines at top and bottom of the searchbar as you can see from the attachment. If you see the black lines and if you don't want them, change;

self.searchBar.searchBar.barTintColor = UIColor.whiteColor()

with

self.searchBar.searchBar.backgroundImage = UIImage(named: "nameOfYourWhiteImage")

And you will have a clean white searchbar. Hope this solves your problem. Good luck!

I suggest using 2 handy extensions for that:

extension UIImage {
    static func imageFromLayer (layer: CALayer) -> UIImage? {
        UIGraphicsBeginImageContext(layer.frame.size)
        guard let currentContext = UIGraphicsGetCurrentContext() else {return nil}
        layer.render(in: currentContext)
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage
    }
}

extension UISearchBar {
    func setCustomBackgroundColor (color: UIColor) {
        let backgroundLayer = CALayer()
        backgroundLayer.frame = frame
        backgroundLayer.backgroundColor = color.cgColor
        if let image = UIImage.imageFromLayer(layer: backgroundLayer) {
            self.setBackgroundImage(image, for: .any, barMetrics: .default)
        }
    }
}

Then just use:

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