Пожалуйста, попробуйте для решения
class ViewController: UIViewController ,UIPickerViewDelegate, UIPickerViewDataSource, UISearchBarDelegate{
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []
var pickerView = UIPickerView()
var searchActive : Bool = false
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
searchBar.inputAccessoryView = pickerView
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
if(searchActive) {
return filtered.count
}
return data.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if searchActive == true{
return filtered[row]
}else{
return data[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if searchActive == true{
searchBar.text = filtered[row]
}else{
searchBar.text = data[row]
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = data.filter({ (text) -> Bool in
let tmp = text
// let range = tmp.rangeOfString(searchText, options: NSString.CompareOptions.CaseInsensitiveSearch)
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return ((range?.lowerBound) != nil)
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.pickerView.reloadAllComponents()
}
}