PiterPan
PiterPan

Reputation: 1802

How to change SearchBar border color

I would like to change grey border color in my Search Bar to white color. Now it looks like that:

search bar

I achieved this effect after using this lines of code, but "inside border" is still grey:

var searchBar: UISearchController!

    self.searchBar.searchBar.backgroundColor = UIColor.whiteColor()
    self.searchBar.searchBar.layer.borderWidth = 3
    self.searchBar.searchBar.layer.borderColor = UIColor.whiteColor().CGColor
    self.searchBar.searchBar.layer.backgroundColor = UIColor.whiteColor().CGColor
    self.searchBar.searchBar.tintColor = UIColor(red: 0.3, green: 0.63, blue: 0.22, alpha: 1)

Can somebody help me in it?

Upvotes: 4

Views: 13075

Answers (3)

screenMonkey MonkeyMan
screenMonkey MonkeyMan

Reputation: 423

You can try self.searchBar.searchBar.searchBarStyle = UISearchBarStyle.minimal to get a clean look with white background, no lines at top or bottom and slightly grey inside to see the actual search field.

Upvotes: 6

Nikita Alexander
Nikita Alexander

Reputation: 567

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)

Upvotes: 0

enoktate
enoktate

Reputation: 735

Result of the code below.

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!

Upvotes: 14

Related Questions