14wml
14wml

Reputation: 4166

How to get rid of border of UISearchBar?

The Problem

I have a UISearchController embedded within a UIView. The searchbar takes up the entire size of the view. However, there's this grey border that I can't figure how to get rid off. I want the search bar to take up the entire size of the view without that pesky grey border. How can I get rid of it?

enter image description here

I've tried

searchController?.searchBar.backgroundImage = UIImage()

But all that does is make the grey border clear (not to mention it makes the searchResultsController of the searchController not show up): enter image description here

I want the border to be gone and the search bar take up the entire frame of the UIView.

Upvotes: 0

Views: 614

Answers (1)

Rakshith Nandish
Rakshith Nandish

Reputation: 639

let SEARCH_BAR_SEARCH_FIELD_KEY = "searchField"
let SEARCH_BAR_PLACEHOLDER_TEXT_KEY = "_placeholderLabel.textColor"

func customiseSearchBar() {

    searchBar.isTranslucent = true
    searchBar.backgroundImage =  UIImage.imageWithColor(color: UIColor.yellow, size: CGSize(width: searchBar.frame.width,height: searchBar.frame.height))

    //modify textfield font and color attributes
    let textFieldSearchBar = searchBar.value(forKey: SEARCH_BAR_SEARCH_FIELD_KEY) as? UITextField
    textFieldSearchBar?.backgroundColor = UIColor.yellow
    textFieldSearchBar?.font = UIFont(name: "Helvetica Neue" as String, size: 18)
    textFieldSearchBar?.setValue(UIColor.yellow, forKeyPath: SEARCH_BAR_PLACEHOLDER_TEXT_KEY)
}

extension UIImage {

    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

This achieves the UI as per your requirement, let me know if you need more customization on this. This is in swift 3 by the way.

Upvotes: 2

Related Questions