首页 > 解决方案 > UIPickerView 委托在以编程方式创建时从不调用

问题描述

我正在UIPickerView以编程方式创建,然后将其添加到UIAlertController. 我还创建了一个名为 的类StringPickerDelegate,它实现了选择器的委托和数据源协议。

这是我创建时的代码UIPickerView

let pickerView = UIPickerView(frame: CGRect(x: 5, y: 20, width: 250, height: 140))
alertController.view.addSubview(pickerView)
let delegate = StringPickerDelegate(items: items) { index, item in
    onItemSelected?(item)
}
pickerView.dataSource = delegate
pickerView.delegate = delegate

这是StringPickerDelegate课程

class StringPickerDelegate: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

    private let items: [String]
    private let didSelectItem: ((Int, String) -> Void)

    init(items: [String], didSelectItem: @escaping ((Int, String) -> Void)) {
        self.items = items
        self.didSelectItem = didSelectItem
    }

    // MARK: UIPickerViewDataSource

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items.count
    }

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

    // MARK: UIPickerViewDelegate

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        didSelectItem(row, items[row])
    }

}

我真的无法理解为什么没有调用这些方法。该类正确实现了两个委托,我还确保在设置委托和数据源之前UIPickerView将其分配并添加为子视图。

编辑:我还尝试了设置委托后,UIAlertController以确保所有视图都已完全实例化,但结果是相同的。

标签: iosswiftuipickerview

解决方案


UIPickerView.delegate被声明为weak(与大多数其他代表一样):

weak var delegate: UIPickerViewDelegate? { get set }

这意味着选择器只持有一个弱引用它。在您的代码执行后,没有其他东西会持有对 的强引用StringPickerDelegate,因此它将被取消初始化!

您需要StringPickerDelegate在 VC 中存储一个实例:

// outside of any method
var pickerDelegate: StringPickerDelegate?

// ...
pickerDelegate = StringPickerDelegate(items: items) { index, item in
    onItemSelected?(item)
}
pickerView.dataSource = pickerDelegate!
pickerView.delegate = pickerDelegate!

推荐阅读