How to make UITextField behave like a UISearchBar in Swift?

Marco Almeida picture Marco Almeida · Oct 19, 2014 · Viewed 26k times · Source

I am working on an new App using UITableView and a UISearchBar in Swift and it's already working fine. But since the final project must have a complete customized searchbar, I had to move to UITextField as the input Outlet because of the customization possibilities.

The problem is that I just can't figure out how to code so that the UITextField behaves like a UISearchBar. Have no idea of how I could filter the UITextField inputs and make the string usable with the UISearchBarDelegate methods.

So anyone could help me out with this?

EDIT: I followed Daniel's help and came up with this code, but it is returning "nil", not working.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

@IBOutlet weak var txtSearchBar: UITextField!
var searchTxt = ""
let prods = ["água", "terra", "ar", "fogo"]
var searchResults:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    txtSearchBar.delegate = self
}


func textFieldDidEndEditing(textField: UITextField) {
    searchTxt = textField.text
    println(searchTxt)
    searchResults = prods.filter({(produtos:String) -> Bool in
        
        let nameMatch = produtos.rangeOfString(self.searchTxt, options: NSStringCompareOptions.CaseInsensitiveSearch)
        
        println(nameMatch)
        return nameMatch != nil})
}

My input was the letters "ar" but it returned "nil", when it shouldn't since one of the array's object is "ar".

Answer

Jayesh Miruliya picture Jayesh Miruliya · Nov 10, 2016

Create uitextfield object:

@IBOutlet var SearchTxt: UITextField!
var search:String=""

@IBOutlet var ListTable: UITableView!
var AllData:Array<Dictionary<String,String>> = []
var SearchData:Array<Dictionary<String,String>> = []

Viewdidload:

override func viewDidLoad()
{
    super.viewDidLoad()

    AllData = [["pic":"list0.jpg", "name":"Angel Mark", "msg":"Hi there, I would like read your...", "time":"just now", "unread":"12"],
               ["pic":"list1.jpg", "name":"John Doe", "msg":"I would prefer reading on night...", "time":"56 second ago", "unread":"2"],
               ["pic":"list2.jpg", "name":"Krishta Hide", "msg":"Okey Great..!", "time":"2m ago", "unread":"0"],
               ["pic":"list3.jpg", "name":"Keithy Pamela", "msg":"I am waiting there", "time":"5h ago", "unread":"0"]
               ]

    SearchData=AllData
}

Search in textfield delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if string.isEmpty
    {
        search = String(search.characters.dropLast())
    }
    else
    {
        search=textField.text!+string
    }

    print(search)
    let predicate=NSPredicate(format: "SELF.name CONTAINS[cd] %@", search)
    let arr=(AllData as NSArray).filtered(using: predicate)

    if arr.count > 0
    {
        SearchData.removeAll(keepingCapacity: true)
        SearchData=arr as! Array<Dictionary<String,String>>
    }
    else
    {
        SearchData=AllData
    }
    ListTable.reloadData()
    return true
}

Search data display in tableview :

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return SearchData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell") as! ListCell

    var Data:Dictionary<String,String> = SearchData[indexPath.row]

    cell.Pic.image=UIImage(named: Data["pic"]!)
    cell.Name.text = Data["name"]
    cell.Msg.text = Data["msg"]
    cell.Time.text = Data["time"]

    cell.selectionStyle = .none
    return cell
}