从选择器视图(选择器轮)中获取选定的值

Get selected value from picker view (picker wheel)

我目前正在使用 XCode 版本 11.3.1 (11C505) 和 Swift 5,关于如何从选择器轮(视图)。这是我的 ViewController.swift

中的相关代码
class ViewController: UIViewController {
    @IBOutlet weak var numberPicker: UIPickerView!
    @IBOutlet weak var test: UILabel!

    private let possibleNums: [Int] = Array(1...16) // Create an array of Ints from 1 to 16
       
    override func viewDidLoad() {
        super.viewDidLoad()
        numberPicker.dataSource = self
        numberPicker.delegate = self
    }
}


extension ViewController: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return possibleNums.count
    }
    // Attempt at getting the selected value, didn't work
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int {
        print(possibleNums[numberPicker.selectedRow(inComponent: 0)])
        test.text = "\(possibleNums[numberPicker.selectedRow(inComponent: 0)])"
    }
}

extension ViewController: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(possibleNums[row])
    }
}

编辑:解决方案也在评论中,所以我想我会把它放在这里以防其他人发现这个: func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int 应该是 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int(缺少 _test.text = "\(possibleNums[numberPicker.selectedRow(inComponent: 0)])" 应该只是 test.text = "\test.text = "\(possibleNums[row])"

test.text = "\(possibleNums[numberPicker.selectedRow(inComponent: 0)])" 更改为:test.text = "\(possibleNums[row])"

你只有一个组件,所以你不需要检查它,只需return行号作为数组的索引。

最简单的方法是将 didSelectRow 函数从

更改为
test.text = "\(possibleNums[numberPicker.selectedRow(inComponent: 0)])"

test.text = "\(possibleNums[rows])"