diff --git a/README.md b/README.md index 83619d8..dba80fa 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,22 @@ mySearchTextField.forceNoFiltering = true // Explicitly hide the results list mySearchTextField.hideResultsList() +// Allow for multiple selections from the list. Default: false +mySearchTextField.allowMultipleSelections = true + +// When using the delegate function with allowMultipleSelections = true, +// remember to add the new selection to the text +mySearchTextField.itemSelectionHandler = { filteredResults, itemPosition in +// Just in case you need the item position +let item = filteredResults[itemPosition] +// Add the selected item to the existing text +if let txt = self.mySearchTextField.text { + self.mySearchTextField.text = txt + " " + item.title +} else { + self.mySearchTextField.text = item.title +} + + /** * Update data source when the user stops typing. * It's useful when you want to retrieve results from a remote server while typing diff --git a/SearchTextField/Classes/SearchTextField.swift b/SearchTextField/Classes/SearchTextField.swift index 2f6ac23..e2e6916 100755 --- a/SearchTextField/Classes/SearchTextField.swift +++ b/SearchTextField/Classes/SearchTextField.swift @@ -13,6 +13,9 @@ open class SearchTextField: UITextField { //////////////////////////////////////////////////////////////////////// // Public interface + /// Allow for multiple selections + open var allowMultipleSelections = false + /// Maximum number of results to be shown in the suggestions list open var maxNumberOfResults = 0 @@ -593,15 +596,34 @@ extension SearchTextField: UITableViewDelegate, UITableViewDataSource { } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if itemSelectionHandler == nil { - self.text = filteredResults[(indexPath as NSIndexPath).row].title + + if allowMultipleSelections { + if let st = self.text { + // this captures if there was another selection in the field + self.text = st + " " + filteredResults[(indexPath as NSIndexPath).row].title + } else { + // this is the first selection - there is nothing else in the field + self.text = filteredResults[(indexPath as NSIndexPath).row].title + } + } else { + // we are not using the multiple selections option + self.text = filteredResults[(indexPath as NSIndexPath).row].title + } + } else { let index = indexPath.row itemSelectionHandler!(filteredResults, index) } - clearResults() + // this will only dismiss the table if allowMultipleSelections is not set + if !allowMultipleSelections { + clearResults() + } + } + } ////////////////////////////////////////////////////////////////////////