iOS Revisited: Search controller

Hot

Post Top Ad

Showing posts with label Search controller. Show all posts
Showing posts with label Search controller. Show all posts

10 Nov 2017

Add Search Bar in Navigation Bar swift | Customize Search Bar

11/10/2017 03:35:00 am 5
In this article we will learn how to add search controller in navigation bar. Customizing search bar like placeholder text, title text, clear button.

Here we are going to use Large Title Navigation bar.

Adding Search Bar In Navigation Bar:

Add the following code in viewDidLoad() method for adding search bar:

if #available(iOS 11.0, *) {
    navigationController?.navigationBar.prefersLargeTitles = true // Navigation bar large titles
    navigationItem.title = "Contacts"
    navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
    navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 0/255, green: 150/255, blue: 136/255, alpha: 1.0)
    
    let searchController = UISearchController(searchResultsController: nil) // Search Controller
    navigationItem.hidesSearchBarWhenScrolling = false
    navigationItem.searchController = searchController
}

Adding Search Bar In Navigation Bar:

Customizing Search Bar:

Change Search Bar Placeholder text & color:

Add the following line of code to change placeholder text and color:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search contacts", attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange])


Change search bar text color:

Add the following line for chaning the text color of search bar:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]


Change cancel button title & color:

For changing cancel button text & color add the following code:

searchController.searchBar.tintColor = UIColor.white
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Dismiss"


Change clear icon:

Add the following code for changing the clear icon:

searchController.searchBar.setImage(UIImage(named: "delete_icon"), for: UISearchBarIcon.clear, state: .normal)


Change search icon:

Add the following code for changing the search icon:

searchController.searchBar.setImage(UIImage(named: "search_icon"), for: UISearchBarIcon.search, state: .normal)


Change Search Bar background color:

For changing the background color add the following code:

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
    if let backgroundview = textfield.subviews.first {
        backgroundview.backgroundColor = UIColor.white
        backgroundview.layer.cornerRadius = 10
        backgroundview.clipsToBounds = true
    }
}


Read More

Post Top Ad