A.I.A.
A.I.A.

Reputation: 189

UIPickerViewDelegate method does not act while subclassing UIPickerView

I'm trying to make a custom date picker. I've subclassed UIPickerView and made it UIPickerViewDataSource and UIPickerViewDelegate in both init(coder:) and init(frame:):

class XKPickerView: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {

override init(frame: CGRect) {
    super.init(frame: frame)
    self.dataSource = self
    self.delegate = self
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    self.dataSource = self
    self.delegate = self
}

(...)
}

But the delegate function pickerView(titleForRow:) is not being called upon the view loads. I think, I'm missing something in init(), but what?

Add: I'm using storyboard to construct views.

Add 2: pickerView code has much dummies yet, but even simple return "abc" in general does not act, because the function itself is not being called (double checked with print() and debugger).

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, 
                forComponent component: Int) -> String? {
    switch component {
    case 0: // day label
        return String(row + 1)
    case 1: // month label (localized)
        return "0"
    case 2: // century label
        return "0"
    case 3: // year of the century label
        return String(row + 1)
    case 4: // era label (localized)
        return "0"
    default:
        return nil
    }
}

Upvotes: 0

Views: 299

Answers (2)

A.I.A.
A.I.A.

Reputation: 189

Thank you all for answers! I was missing, that I've added a pickerView.delegate = self in ViewDidLoad() of a corresponding view controller. What a disgrace :)

Upvotes: 1

DonMag
DonMag

Reputation: 77462

Not sure what's going on with your attempt, but I just did this and it's working without issue...

class MyPickerView: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.dataSource = self
        self.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.dataSource = self
        self.delegate = self
    }

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

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "Row \(row)"
    }

}

That's the entire class.

Upvotes: 2

Related Questions