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".
With the help of @Daniel T. I managed to solve the problem with the following code:
func textFieldShouldReturn(textField: UITextField) -> Bool {
isFiltered = true
searchResults = prods.filter({(coisas:String) -> Bool in
let stringMatch = coisas.rangeOfString(textField.text)
return stringMatch != nil
})
println(searchResults.description)
textField.resignFirstResponder()
table.reloadData()
return true
}
Thanks @Daniel T.