derdida
derdida

Reputation: 14904

Set cornerRadius for UISearchBar?

I would like to change the cornerRadius property of an UISearchbar, but it is not working. I tried with:

if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = Color.text.primary // this is working
        if let backgroundView = textfield.subviews.first {
            backgroundView.layer.cornerRadius = 2 // not working
            backgroundView.clipsToBounds = true
        }
    }

Any ideas? If i set the backgroundView to another Color, it works as expected (so the BackgroundView is here)

Upvotes: 3

Views: 2746

Answers (1)

Samah
Samah

Reputation: 1234

It looks like that background view has custom rendering code that forces the rounded corners. What you can try is hiding that view, and manually configuring the textfield to look the same.

if let textField = self.searchBar.subviews.first?.subviews.flatMap({ $0 as? UITextField }).first {
    textField.subviews.first?.isHidden = true
    textField.textColor = Color.text.primary
    textField.layer.backgroundColor = UIColor.white.cgColor
    textField.layer.cornerRadius = 2
    textField.layer.masksToBounds = true
}

Note that this could break in future versions of iOS if Apple decide to change the way UISearchBar textfields are structured.

Edited to not use value(forKey:).

Upvotes: 5

Related Questions