Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar custom corners

I'm trying to create a search bar like this:

enter image description here

But I'm noticing that I'm probably going to have to replace the search bar with my own image because the search bar corners comes out wrong when I set:

self.searchController.searchBar.layer.cornerRadius = 50 // I've tried other numbers besides this too with no luck
self.searchController.searchBar.clipsToBounds = true

enter image description here

If I set this:

self.searchController.searchBar.layer.cornerRadius = self.searchController.searchBar.bounds.height/2

The search bar comes out like this:

enter image description here

Which still isn't exact like in the image.

Is there a way to replace the left and right side of the textfield with an image that way I can use the rounded corners from my custom search bar?

like image 655
Thomas Avatar asked Jul 20 '15 16:07

Thomas


3 Answers

I am using this code UISearchBar but you can use this code with UISearchController.

    let searchBar = UISearchBar()
                searchBar.sizeToFit()
                searchBar.placeholder = "Search"
                navigationItem.titleView = searchBar

                if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
                    textfield.textColor = UIColor.blue
                    if let backgroundview = textfield.subviews.first {
                        // Background color
                        backgroundview.backgroundColor = UIColor.white
                        // Rounded corner
                        backgroundview.layer.cornerRadius = 14;
                        backgroundview.clipsToBounds = true;
                    }
                }
like image 132
Usman Avatar answered Nov 04 '22 08:11

Usman


You should change the radius of searchTextField inside UISearchBar .

you can do that like this :

searchBar.searchTextField.layer.cornerRadius = 20
searchBar.searchTextField.layer.masksToBounds = true

* searchBar is an outlet of UISearchBar from storyBoard

like image 24
Hamid Reza Ansari Avatar answered Nov 04 '22 06:11

Hamid Reza Ansari


The issue here is you are setting the corner radius on the UISearchBar, not the UITextField inside it. You can do some sort of hack to get the UITextField, but that's not really recommended.

As you mentioned in your question, you'll need to use custom images and the methods shown here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/#//apple_ref/doc/uid/TP40007529-CH3-SW40

like image 6
mbottone Avatar answered Nov 04 '22 07:11

mbottone