Reputation: 107
How can I sort this Array in my PickerView ? I am using Swift 3.
Upvotes: 1
Views: 738
Reputation: 688
Swift 3.1:
var arr = ["aaa","zz","ddd","mnm","zzzz"]
var newArr = arr.sorted()
print(newArr)
//log: ["aaa", "ddd", "mnm", "zz", "zzzz"]
Upvotes: 0
Reputation: 72450
Instead of sorting array every time in titleForRow
you need to sort it once after you initialized your stores
array.
stores.sort { $0.name < $1.name }
Now stores
array is sorted by name property now simply return the name from titleForRow
method.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return stores.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return stores[row].name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(stores[row].name)
}
Upvotes: 2