0

如何创建生成 20 到 80 数字的代码?使用pickerviewlet年龄= [“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 而无需需要这么多文字

4

1 回答 1

0

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

let ages = (20...80).map { "\($0)" }

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
}
于 2020-07-03T01:07:12.877 回答