Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background of UISearchBar's textField

Tags:

I'm struggling with this for a while now. Have searched everywhere but the solution provided only works with objective-c. Which consists in

UITextField *txt = [_searchBar valueForKey:@"_searchField"];

Although some might say that this is protected API and Apple might refuse an app with such code.

So, now I've tried so many ways to work this out and it's not working at all. My code is this:

searchBar = UISearchBar(frame: CGRectMake(0, 0, 320.0, 30.0))
searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.layer.cornerRadius = 15
searchBar.delegate = self

searchBar.backgroundColor = UIColor.whiteColor()

if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1{
    // Load resources for iOS 6.1 or earlier
    searchBar.placeholder = "Search";
} else {
    // The following "hack" (if we can call that) breaks the UI for different size devices.
    // Load resources for iOS 7 or later
    searchBar.placeholder = "Search                                         ";
}

This gives me the bizarre result: enter image description here

While what I want is just the textfield inside the UISearchBar to have a white background and the SearchBar itself have a cornerRadius of, say, 15.

How can I do this?

Thanks so much in advance

like image 701
Patrick Bassut Avatar asked Jan 20 '15 22:01

Patrick Bassut


People also ask

How do I change the background color of a textfield in Swift?

To change the background color in a UITextField you first need to use a different style of text field to the "rounded" style (such as the "no border" style) either in Interface Builder or programmatically.

How do I change the color of my UISearchBar in Swift?

Change Search Bar Default Image Color The left hand default search image in UISearchBar represents the left view of the UITextField. The Image is rendered to change it to the desired colour. @IBOutlet weak var searchBar: UISearchBar! Hope it will help you in customising the UISearchBar in your app.


1 Answers

You have to access the UITextField inside the UISearchBar. You can do that by using valueForKey("searchField")

var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField

textFieldInsideSearchBar?.textColor = yourcolor
textFieldInsideSearchBar?.backgroundColor = backgroundColor
...

there you can change any parameters like textColor or backgroundColor of the UITextField

like image 173
helgetan Avatar answered Sep 27 '22 19:09

helgetan