Custom UIPickerView example

pickerview_custom

ref – http://stackoverflow.com/questions/3061401/respondstoselector-not-found-in-protocols

CustomPickerEx

Description

We are going to create a custom UIPickerView. This Picker View get the string of your selection, then send the delegating class the result. Hence a UIViewController can create this custom class, conform to the protocol, connect the delegate, and start receiving strings of the selected entries in the picker view.

Create class and override

Implement the protocol, create the delegate

For our case, we are going to create a single delegate which forces the UIViewController to implement our single delegate’s methods.

All default UIPickerViewDelegate and UIPickerViewDataSource will delegate to our custom RTPickerView.

If you want to group your custom delegate methods along with UIPickerViewDelegate, UIPickerViewDataSource, under RTPickerDelegate, you can declare it like so:

In your ViewController, when you conform to RTPickerDelegate
and you go self.pickerView.delegate = self,

Then you will be receiving all messages from all delegates.

However, for the sake of demonstration, we are going to create a custom protocol. When the ViewController uses it, it can receive 2 delegates. One is ‘delegate’ from UIPickerViewDataSource and UIPickerViewDelegate. One is RTPicker_Delegate, which is for taking care of our custom protocol methods.

That way, you can pick and choose which protocol you will want to conform to.

The RTPicker_Delegate delegate that we want our calling UIViewController to access should be weak. It should not be strong because as an object, we don’t want the controlling UIViewController to keep us in memory.

Implementation

Our Custom object conforms to View Delegates and Data Source delegates. Thus, we
take care of these protocol in this class. The calling ViewController is welcome to access the delegate property, and then implement these protocol methods too if it wants.

UIPickerViewDataSource methods

UIPickerViewDelegate protocol methods

RTPickerDelegate protocol method

When we are processing didSelectData, we don’t want the calling UIViewController to suddenly disappear on us. Thus, we strong ViewController temporarily. The local stack has a strong pointer on it, it makes the delegated UIViewController process messages, and this method will finish. Our strongDelegate is declared on the stack, and thus, will pop. Free-ing this class from the UIViewController

How to Use

Conform to the protocol

Create the object, make sure you add it to the UIViewController, and then connect the delegate. After connecting the delegate, all messages from that particular action which triggers the protocol method, will be sent to the ViewController for answers. You, as the developer of the UIViewController will need to implement it.

Implementation of the protocol method