Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cornerRadius for UISearchBar?

Tags:

swift

ios11

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)

like image 976
derdida Avatar asked Jul 01 '26 00:07

derdida


1 Answers

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:).

like image 82
Samah Avatar answered Jul 03 '26 14:07

Samah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!