UIPickerView没有出现

时间:2018-05-26 22:35:23

标签: ios swift uipickerview

我有DrinkVolumePickerController.swift我试图保留委托和数据源逻辑以使它们远离我的ViewController

import UIKit

class DrinkVolumePickerController: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

    var quantities: [(label: String, ml: Int)] = [("Pint", 568), ("Can", 330)]

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

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

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return quantities[row].label + " - " + String(quantities[row].ml)
    }

}

在我的ViewController中我有

import UIKit

class AddDrinkViewController: UIViewController {

    lazy var drinkVolumeControl: UIPickerView! = {
        let view = UIPickerView()
        view.translatesAutoresizingMaskIntoConstraints = false

        let controller = DrinkVolumePickerController()
        view.delegate = controller
        view.dataSource = controller

        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(drinkVolumeControl)
        view.setNeedsUpdateConstraints()
    }
}

当我在模拟器中运行时,我没有看到Picker,但我可以在DebugViewHeirarchy中看到它。

如果我将所有逻辑移回ViewController并将delegatedatasource更改为self,那么它会正常加载。

我只是不明白为什么它不能在外部文件中使用它们?

1 个答案:

答案 0 :(得分:0)

您遇到了内存管理问题。

移动线:

let controller = DrinkVolumePickerController()

AddDrinkViewController的属性,而不是drinkVolumeControl内的局部变量。