Search code examples
swiftxcodeuisearchbarsearchbar

want to create a search bar like google in swift


I have an array like ["apple","appear","Azhar","code","BCom"] etc. This array contain more than half a million of records.

Now what I want to do, is to place a UISearchBar like in google and then whenever user types a text, then the dropdown list would appear with all the results containing this text and user could select one from the list.

For example - if the user types "a", then "apple","appear" and "Azhar" would appear in a drop-down list.

I don't want to use a UITableView or anything else to load the records. Whenever user types any word it should collect records from the array and make a drop down to display them.

How can I do this? Suggestions required please.


Solution

  • Pretty simple code that would do the trick, the search bar filter is easy, as for the drop down menu i use a third party Pod named 'DropDown' that is very easy to use : https://github.com/AssistoLab/DropDown

    import UIKit
    import DropDown
    
    class ViewController: UIViewController, UISearchBarDelegate {
    
    var data: [String] = ["apple","appear","Azhar","code","BCom"]
    var dataFiltered: [String] = []
    var dropButton = DropDown()
    
    @IBOutlet weak var searchBar: UISearchBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        dataFiltered = data
    
        dropButton.anchorView = searchBar
        dropButton.bottomOffset = CGPoint(x: 0, y:(dropButton.anchorView?.plainView.bounds.height)!)
        dropButton.backgroundColor = .white
        dropButton.direction = .bottom
    
        dropButton.selectionAction = { [unowned self] (index: Int, item: String) in
            print("Selected item: \(item) at index: \(index)") //Selected item: code at index: 0
        }
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        dataFiltered = searchText.isEmpty ? data : data.filter({ (dat) -> Bool in
            dat.range(of: searchText, options: .caseInsensitive) != nil
        })
    
        dropButton.dataSource = dataFiltered
        dropButton.show()
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        for ob: UIView in ((searchBar.subviews[0] )).subviews {
            if let z = ob as? UIButton {
                let btn: UIButton = z
                btn.setTitleColor(UIColor.white, for: .normal)
            }
        }
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = false
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.text = ""
        dataFiltered = data
        dropButton.hide()
    }
    }
    

    enter image description here