Reputation: 2048
I am learning the use of UIPickerView objects and creating one programatically. Given that it uses a delegate to call if a selection is made; what is the standard practise for getting that information to the main view controller that instantiated the picker?
I am thinking that I will use a selector to allow the delegate to send the selected row to the view controller; is there a better way?
Any assistance from someone who uses these objects regularly would be appreciated.
Upvotes: 1
Views: 202
Reputation: 5707
Typically, your UIViewController
that instantiated the UIPickerView
will also act as its delegate (and datasource). In this case, you would assign your view controller to be the delegate of the picker, such as
[myPickerView setDelegate:self];
Then, you'll implement the method - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
inside your view controller. When you assign an object to be the delegate of another object, you're saying "Hey, this object knows what to do when it gets sent these delegate messages". In your case, you're saying "My main controller knows what to do when the picker sends it the didSelectRow:inComponent: message".
In doing this, you won't need to do any of that use-a-selector-to-allow-the-delegate-to-send-the-selected-row-to-the-view-controller nonsense. That is the whole point of the delegate! UIPickerView
is "delegating" work to some other object (your controller) that knows what to do with the information contained within the selected row of the picker.
Upvotes: 1
Reputation: 11728
Implement the delegate method - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
so that whenever a row is selected it will call this method.
You can do something like this:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(@"row %d selected in component %d", row, component);
}
Upvotes: 1