Search code examples
iosswiftuipickerview

UIPickerView not appearing


I have DrinkVolumePickerController.swift where I'm trying to keep the delegate and datasource logic to keep them out of my 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)
    }

}

In my ViewController I have

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()
    }
}

When I run this in the simulator I don't see the Picker, but I can see it in the DebugViewHeirarchy.

If I move all the logic back into the ViewController and change the delegate and datasource to self then it loads fine.

I just don't get why it's not working having them in an external file?


Solution

  • You have a memory management problem.

    Move the line:

    let controller = DrinkVolumePickerController()
    

    to be a property of your AddDrinkViewController instead of being a local variable inside drinkVolumeControl.