选择器视图生成数字 20 到 80

picker view generate number 20 to 80

如何创建生成 20 到 80 之间数字的代码?使用 pickerviewlet ages = ["20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31","32","33","34","35","36","37","38","39","40","41","42","43" ", "44", "45", "46", "47", "48", "49", "50"] 我目前有这个,但我想知道是否有办法将它扩展到 80 而不需要那么多文本

您可以使用范围创建数组:

let ages = (20...80).map { "\([=10=])" }

map 调用将每个数字转换为字符串。


更好的选择是不将所有年龄存储在内存中的数组中。请注意,行号 + 20 等于您要在选择器视图的该行显示的年龄。所以你可以像这样实现选择器视图方法:

var selectedAge: Int?
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    61 // there are 61, not 60, numbers from 20 to 80!
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    "\(row + 20)" // for row 0, the row says 20, for row 1, it says 21, for row 2, it says 22, and so on
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // calculate the selected age using the same formula
    selectedAge = row + 20
}