Search code examples
iosswiftuipickerview

Subclass UIPickerView swift


I'm trying to create a subclass of UIPickerView so I can use my picker in multiple views. I'm trying to call my picker programmatically as inputView of a UITextField but I can't figure out how to initialise it correctly. I'm in doubt if this is the right approach and how I can get it to work. I hope any of you can help me.

UIPickerView subclass:

import UIKit

 class GroupPicker : UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource{

    var cdm = CoreDataManager()
    var groupObjList : [Group]!

    init() {
       groupObjList = cdm.groupList()
    }

    //MARK: - Delegates and data sources

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

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

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return groupObjList[row].title
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        println("picked \(groupObjList[row].title)")

    }        
}

How I try to call it in the view controller:

override func viewDidLoad() {
    super.viewDidLoad()

    groupPicker = GroupViewPicker()  //instead of UIPickerView()
    groupField.inputView = groupPicker
}

Solution

  • It was easy like this.

    GroupPicker : UIPickerView {
    
            override init(frame: CGRect){
                super.init(frame: frame)
                self.groupObjList = cdm.groupList()
            } 
    }
    

    Call it:

    viewDidLoad() {
        groupField.inputView = GroupPicker(frame: CGRectZero)
    }