Manage a UIPickerView from an External Class - Using Swift

别说谁变了你拦得住时间么 提交于 2019-12-04 06:46:44

Subclass Pickerview

class MyPickerView: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {

    var oficinas = ["oficina 1", "Oficinas 2", "Oficina 3"]

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

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

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

Main View Controller with Outlet for the PickerView

class MainViewController: UIViewController {
    @IBOutlet weak var myPickerView: UIPickerView!

    var pickerOficinas: MyPickerView!

    override func viewDidLoad() {
        //how do I hookup my picker view class
        pickerOficinas = MyPickerView()
        myPickerView.delegate = pickerOficinas
        myPickerView.dataSource = pickerOficinas
    }
}

I think you may have got hold of the wrong end of the stick!

Why do you want to make the picker its own delegate? The point of having a delegate is that it can tell its delegate what has been selected etc.

I would think that what you should be doing is making your view controller conform to UIPickerViewDelegate and make it the delegate of the picker and put the logic for whatever you want to happen when an item is picked in those delegate methods. I can't see any other way of 'telling' your view controller about the picker.

Also, if you reference to your picker is weak, then unless you are holding a strong reference to it somewhere else, at all times (eg it is part of the view hierarchy) it will be deallocated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!