2
votes

I have a UiSearchbar within my Navigation Bar. The SearchBar style is minimal. I am on iOS 8, using a SearchController (no SearchDisplayController) and Swift.

  1. I would like to set the placeholder and the icon color to white. Is this possible? All that I've found so far seems to be outdated or the author is not sure whether this code will be approved by Apple.

  2. I would like to get rid of the cancel Button, but when I try this: searchController.searchBar.showsCancelButton = false within the viewDidLoad, the cancel button still shows up.

I must say, I am creating the searchBar programmatically..

1

1 Answers

6
votes

For your first problem, you could access the UITextField of your UISearchbar and edit the placeholder color:

var textfield:UITextField = searchBar.valueForKey("searchField") as UITextField

//Set the foregroundcolor of the placeholder
var attributedString = NSAttributedString(string: "your placeholdertext", attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])

textfield.attributedPlaceholder = attributedString

Then to also set the glass-color you have to access the leftView of your UITextField:

//Get the glass icon
var iconView:UIImageView = textfield.leftView as UIImageView
//Make the icon to a template which you can edit
iconView.image = iconView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
//Set the color of the icon
iconView.tintColor = UIColor.whiteColor()

To hide the cancel-button in your UISearchbar you can use the searchBarShouldBeginEditing delegate method and hide it. Just make sure to add the UISearchBarDelegate first and set the delegate to your searchbar:

 class YourviewController:UIViewController, UISearchBarDelegate{

    override func viewDidLoad() {
        searchbar.delegate = self
    }

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        searchBar.setShowsCancelButton(false, animated: true)
        return true
    }
}