How to search for Crazy People…

by sisccr

Some times Its so much useful to have a search feature in our apps. It’s so much easy to search the table view in swift.

I have a basic project already setup which  a table view as a list of names.

Screen Shot 2016-12-19 at 8.23.14 PM.png

I have defined two outlets for UITextField and UITableView in my ViewController Class.

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var txtSearch: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    let names: [String] = [
        "Ccr", "Shishir", "Da ri",
        "Bibek", "Manoj", "Amrit",
        "An Gee", "Dee J", "Ajeet",
        "Ashik", "Be Nod", "Samina",
        "guru", "aarko guru", " aani guru ko dup"
    ]
    var searchText: String = ""
    
    var filterednames: [String]  {
        let searchText = self.searchText.lowercased()
        return names.filter({
            name in
                return searchText.isEmpty || name.lowercased().contains(searchText)
        }).sorted(by: { (name, _) -> Bool in
            return name.hasPrefix(searchText) ?? false
        })
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        txtSearch.addTarget(self,
                            action: #selector(ViewController.filter(sender:)),
                            for: UIControlEvents.editingChanged
        )
    }
    
    func filter(sender: UITextField) {
        searchText = sender.text!
        tableView.reloadData()
    }
}


extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return filterednames.count
    }
    
    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let name = filterednames[indexPath.row]
        cell.set(name: name)  // see extension below.
        return cell
    }
}

extension UITableViewCell {
    func set(name: String) {
        self.textLabel?.text = name
    }
}

So, That’s how we find crazy people.

Advertisements