Thursday, July 15, 2010

Using Two PickerViews together

Using two PickerViews together.

Expanding upon the previous tutorial, we will explore how to use two PickerViews together. Such is useful for ‘converter’ like applications, eg. currency converter, units converter.

Below figure shows an example of a bible units converter. that uses two PickerViews.

To have two PickerViews in your app, first drag and drop another PickerView into you xib file .. Declare the Outlet for it. Remember to click them to File’s owner.

The code where you have to edit are the below. Include an if-else condition based on the pickerView that triggered the method. I have two pickerViews, one named pickerView, the other pickerView2. Check which pickerView triggered the method, and set the corresponding label to the value of that particular pickerView.

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([thePickerView isEqual:self.pickerView])
mlabel.text= [arrayNo objectAtIndex:row];
else
mlabel2.text= [arrayNo2 objectAtIndex:row];
}

Have a similar if-else condition to return the no. of rows in each PickerView and also the title for each pickerView cell.
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
if([pickerView isEqual:self.pickerView])
return [arrayNo count];
else
return [arrayNo2 count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
if([pickerView isEqual:self.pickerView])
return [arrayNo objectAtIndex:row];
else
return [arrayNo2 objectAtIndex:row];
}

So there you go, how to use two picker Views together.

1 comment:

  1. Hi Jason. I have a question regarding two pickerview connections.When I select "shekel" from first pickerview, and select "grams" from second pickerview, how to connect between two pickerviews so that it can covert fron shekel to grams and displays the result in the corresponding result. Thank you in advance.

    ReplyDelete