Custom Uisearchbar with Uisearchcontroller

How to customize the searchBar in a UISearchController?

set attributedPlaceholder for textfield of search bar

@IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {

textfield.backgroundColor = UIColor.red
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.white
}

}

Here is result:

Sample Image

Update:

I think, this may help you: how to change uitextfield color in searchcontroller?

Just apply your color combination in this code and see.

if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white

if let textfield = scb.value(forKey: "searchField") as? UITextField {
//textfield.textColor = // Set text color
if let backgroundview = textfield.subviews.first {

// Background color
backgroundview.backgroundColor = UIColor.white

// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;

}
}

if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false

}

Result:

Sample Image

Connect UISearchController to UISearchBar without embedding the search bar in the tableview or in the navigation bar

You did all the hard work and the thing that you miss is fairly trivial to what you did.

Basically you should add the UISearchBar resultSearchController!.searchBar as the subview to the view using the code. I don't think it would be possible with Storyboard, that could be what confused you.



Related Topics



Leave a reply



Submit