Hi Friends , Earlier we read about how to implement UISearchbar in objective C.

Today We will read how to implement the same using Swift. (Xcode7.3.1)

 

Steps:

  1. Create a new Xcode Project (Lets say SearchControllerinSwift2)
  2. Now go To YourView Controller and add a tableView and make proper connection and set the dataSource and delegate Methods.
  3.  Now go to File – New File  – Swift and create a new empty Swift File and name it as Countries.

Screen Shot 2016-10-16 at 1.30.53 AM.png4 . Now go to that File and the below data which we will use for populating the Array.

import Foundation

public enum Countries

{

    static let list = [“Afghanistan”, “Akrotiri”, “Albania”, “Algeria”, “American Samoa”, “Andorra”, “Angola”, “Anguilla”, “Antarctica”, “Antigua and Barbuda”, “Argentina”, “Armenia”, “Aruba”, “Ashmore and Cartier Islands”, “Australia”, “Austria”, “Azerbaijan”, “The Bahamas”, “Bahrain”, “Bangladesh”, “Barbados”, “Bassas da India”, “Belarus”, “Belgium”, “Belize”, “Benin”, “Bermuda”, “Bhutan”, “Bolivia”, “Bosnia and Herzegovina”, “Botswana”, “Bouvet Island”, “Brazil”, “British Indian Ocean Territory”, “British Virgin Islands”, “Brunei”, “Bulgaria”, “Burkina Faso”, “Burma”, “Burundi”, “Cambodia”, “Cameroon”, “Canada”, “Cape Verde”, “Cayman Islands”, “Central African Republic”, “Chad”, “Chile”, “China”, “Christmas Island”, “Clipperton Island”, “Cocos (Keeling) Islands”, “Colombia”, “Comoros”, “Democratic Republic of the Congo”, “Republic of the Congo”, “Cook Islands”, “Coral Sea Islands”, “Costa Rica”, “Cote d’Ivoire”, “Croatia”, “Cuba”, “Cyprus”, “Czech Republic”, “Denmark”, “Dhekelia”, “Djibouti”, “Dominica”, “Dominican Republic”, “Ecuador”, “Egypt”, “El Salvador”, “Equatorial Guinea”, “Eritrea”, “Estonia”, “Ethiopia”, “Europa Island”, “Falkland Islands (Islas Malvinas)”, “Faroe Islands”, “Fiji”, “Finland”, “France”, “French Guiana”, “French Polynesia”, “French Southern and Antarctic Lands”, “Gabon”, “The Gambia”, “Gaza Strip”, “Georgia”, “Germany”, “Ghana”, “Gibraltar”, “Glorioso Islands”, “Greece”, “Greenland”, “Grenada”, “Guadeloupe”, “Guam”, “Guatemala”, “Guernsey”, “Guinea”, “Guinea-Bissau”, “Guyana”, “Haiti”, “Heard Island and McDonald Islands”, “Holy See (Vatican City)”, “Honduras”, “Hong Kong”, “Hungary”, “Iceland”, “India”, “Indonesia”, “Iran”, “Iraq”, “Ireland”, “Isle of Man”, “Israel”, “Italy”, “Jamaica”, “Jan Mayen”, “Japan”, “Jersey”, “Jordan”, “Juan de Nova Island”, “Kazakhstan”, “Kenya”, “Kiribati”, “North Korea”, “South Korea”, “Kuwait”, “Kyrgyzstan”, “Laos”, “Latvia”, “Lebanon”, “Lesotho”, “Liberia”, “Libya”, “Liechtenstein”, “Lithuania”, “Luxembourg”, “Macau”, “Macedonia”, “Madagascar”, “Malawi”, “Malaysia”, “Maldives”, “Mali”, “Malta”, “Marshall Islands”, “Martinique”, “Mauritania”, “Mauritius”, “Mayotte”, “Mexico”, “Federated States of Micronesia”, “Moldova”, “Monaco”, “Mongolia”, “Montserrat”, “Morocco”, “Mozambique”, “Namibia”, “Nauru”, “Navassa Island”, “Nepal”, “Netherlands”, “Netherlands Antilles”, “New Caledonia”, “New Zealand”, “Nicaragua”, “Niger”, “Nigeria”, “Niue”, “Norfolk Island”, “Northern Mariana Islands”, “Norway”, “Oman”, “Pakistan”, “Palau”, “Panama”, “Papua New Guinea”, “Paracel Islands”, “Paraguay”, “Peru”, “Philippines”, “Pitcairn Islands”, “Poland”, “Portugal”, “Puerto Rico”, “Qatar”, “Reunion”, “Romania”, “Russia”, “Rwanda”, “Saint Helena”, “Saint Kitts and Nevis”, “Saint Lucia”, “Saint Pierre and Miquelon”, “Saint Vincent and the Grenadines”, “Samoa”, “San Marino”, “Sao Tome and Principe”, “Saudi Arabia”, “Senegal”, “Serbia”, “Montenegro”, “Seychelles”, “Sierra Leone”, “Singapore”, “Slovakia”, “Slovenia”, “Solomon Islands”, “Somalia”, “South Africa”, “South Georgia and the South Sandwich Islands”, “Spain”, “Spratly Islands”, “Sri Lanka”, “Sudan”, “Suriname”, “Svalbard”, “Swaziland”, “Sweden”, “Switzerland”, “Syria”, “Taiwan”, “Tajikistan”, “Tanzania”, “Thailand”, “Tibet”, “Timor-Leste”, “Togo”, “Tokelau”, “Tonga”, “Trinidad and Tobago”, “Tromelin Island”, “Tunisia”, “Turkey”, “Turkmenistan”, “Turks and Caicos Islands”, “Tuvalu”, “Uganda”, “Ukraine”, “United Arab Emirates”, “United Kingdom”, “United States”, “Uruguay”, “Uzbekistan”, “Vanuatu”, “Venezuela”, “Vietnam”, “Virgin Islands”, “Wake Island”, “Wallis and Futuna”, “West Bank”, “Western Sahara”, “Yemen”, “Zambia”, “Zimbabwe”]

}

5. Now go to your ViewController.m . Here first we will create an object of

UISearchController and set its properties. then we will write the dataSource methods of tableView and function to implement the search logic.

import UIKit

class ViewController: UIViewController,UISearchResultsUpdating {

    

    @IBOutlet weak var countryTable: UITableView!

    var searchArray = [String]()

    var countrySearchController: UISearchController = ({

        let controller = UISearchController(searchResultsController: nil)

        controller.hidesNavigationBarDuringPresentation = false

        controller.dimsBackgroundDuringPresentation = false

        controller.searchBar.searchBarStyle = .Default

        controller.searchBar.sizeToFit()

        return controller

    })()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        // Configure countryTable

        countryTable.tableHeaderView = countrySearchController.searchBar

        countrySearchController.searchResultsUpdater = self

    }

    

    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(true)

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    {

        switch countrySearchController.active {

        case true:

            return searchArray.count

        case false:

            return Countries.list.count

        }

    }

    

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

    {

        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:“cell”)

        cell.textLabel?.text = “”

        switch countrySearchController.active {

        case true:

            cell.textLabel?.text! = searchArray[indexPath.row]

            return cell

        case false:

            cell.textLabel?.text! = Countries.list[indexPath.row]

            return cell

        }

    }

    

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

    {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    }

    

    func updateSearchResultsForSearchController(searchController: UISearchController)

    {

        searchArray.removeAll(keepCapacity: false)

        

        let range = searchController.searchBar.text!.characters.startIndex ..< searchController.searchBar.text!.characters.endIndex

        var searchString = String()

        

        searchController.searchBar.text?.enumerateSubstringsInRange(range, options: .ByComposedCharacterSequences, { (substring, substringRange, enclosingRange, success) in

            searchString.appendContentsOf(substring!)

            searchString.appendContentsOf(“*”)

        })

        

        let searchPredicate = NSPredicate(format: “SELF LIKE[cd] %@”, searchString)

        let array = (Countries.list as NSArray).filteredArrayUsingPredicate(searchPredicate)

        searchArray = array as! [String]

        countryTable.reloadData()

    }

}

Now just run the code and see the output.

You can download the whole source code from here.

Please do share Your reviews.

Enjoy Coding 🙂

Advertisements