简体   繁体   English

如何在Swift 3中对这个数组进行排序? (选取器视图)(核心数据)

[英]How can I sort this Array in Swift 3 ? ( Picker View ) ( Core Data )

在此处输入图片说明

在此处输入图片说明

How can I sort this Array in my PickerView ? 如何在PickerView中对该数组排序? I am using Swift 3. 我正在使用Swift 3。

Instead of sorting array every time in titleForRow you need to sort it once after you initialized your stores array. 无需每次在titleForRow中对数组进行排序, titleForRow需要在初始化stores数组后对其进行一次排序。

stores.sort { $0.name < $1.name }

Now stores array is sorted by name property now simply return the name from titleForRow method. 现在stores数组是按name属性排序的,现在只需从titleForRow方法返回名称titleForRow

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)
}

Swift 3.1: Swift 3.1:

var arr = ["aaa","zz","ddd","mnm","zzzz"]
var newArr = arr.sorted()
print(newArr)
//log: ["aaa", "ddd", "mnm", "zz", "zzzz"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM