Search code examples
iosstoryboarduipickerview

ios/xcode/objective-c: UIPickerView Not Displaying


I have a UIPickerView that shows up in storyboard but is invisible or at best a colored block if I change the background color when I compile the program. Do I need to populate it with data for it to display, i.e. does it no longer show Cupertino, Mountain View etc. once compiled?

BTW, I am trying to populate picker view with data but still invisible:

    code:
    in .h file:
@interface pickerVC : UIViewController<UIPickerViewDelegate,UIPickerViewDataSource>
    @property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
    @property (strong, nonatomic) IBOutlet UILabel *color;
    @property (strong, nonatomic)          NSArray *myArray;

    in viewdidload;
       UIPickerView *pickerView;
        pickerView.delegate = self;
        _myArray  = [[NSArray alloc]         initWithObjects:@"Blue",@"Green",@"Orange",@"Purple",@"Red",@"Yellow" , nil];


    //PICKER METHODS
    // tell the picker how many rows are available for a given component
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
     //   NSUInteger numRows = 3;

        return _myArray.count;
    }

    // tell the picker how many components it will have
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
        return 1;
    }

    // tell the picker the title for a given component
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
        NSString *title;

        title = _myArray[row];

        return title;
    }

    // tell the picker the width of each row for a given component
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
        int sectionWidth = 300;

        return sectionWidth;
    }
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"Selected Row %d", row);
    switch(row){
        // Handle the selection
    }

Solution

  • Yes it is not displaying. You have to set delegate and datasource of picker view and implement delegate methods in your controller.m file. e.g.

    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 1;
    }
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        return 10;
    }
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        return @"ABC";
    }