Search code examples
iosswiftcocoauipickerview

Outsourcing the delegate and datasource of a picker to another class in swift


I am creating more than one picker in one view controller, so I have to use separate cocoa touch classes to handle the datasource and delegate methods of each of them. I have this code:

myPicker.delegate = CustomPickerViewController

myPicker.dataSource = CustomPickerViewController

In this case, CustomPickerViewController is a cocoa touch class in a separate file which has the required UIPickerViewDelegate and UIPickerViewDataSourcemethods implemented. So, what should I be assigning to the above properties in order to handle populating a picker view using the CustomPickerViewController class?


Solution

  • Each picker should get its own instance of CustomPickerViewController.

    myPicker.delegate = CustomPickerViewController()
    myPicker.dataSource = myPicker.delegate
    
    anotherPicker.delegate = CustomPickerViewController()
    anotherPicker.dataSource = anotherPicker.delegate