Search code examples
iosobjective-cuiviewuipickerview

How do I show two different object types in UIPickerView for two different components?


I have a picker with two components. In component 0 (kCardComponent) I want NSStrings to appear. In component 1 (kSuitComponent) I want UIView. Here is the code from my picker view. The program crashes, I'm assuming because it's returning an NSString when it should be returning a UIView in this method

- (UIView *)pickerView:(UIPickerView *)pickerView
        viewForRow:(NSInteger)row
      forComponent:(NSInteger)component reusingView:(UIView *)view {
if (component == kSuitComponent) {
    UIImage *image = self.suitImages[row];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    return imageView;
}
else
    return (UIView*)self.cardNumber[row];
}

I've tried creating another picker view -(NSString*)pickerView, but that did not work. What should I do?


Solution

  • You can't return strings from this delegate method, only views. Since you need a view for one component, you need a view for all. What you need to do is create a UILabel and set its text to the string you have.

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
        if (component == kSuitComponent) {
            UIImage *image = self.suitImages[row];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            return imageView;
        } else {
            NSString *text = self.cardNumber[row];
            UILabel *label = ... // create label
            label.text = text;
            return label;
        }
    }