1

I'd like to create a fairly complex row in my UIPicker. All of the examples I've seen create a view from scratch like so...

- (UIView *) pickerView:(UIPickerView *)pickerView
viewForRow:(NSInteger)row
forComponent: (NSInteger)component reusingView:(UIView *)view
{
    CGRect cellFrame = CGRectMake(0.0, 0.0, 110.0, 32.0);
    UIView *newView = [[[UIView alloc] initWithFrame:cellFrame] autorelease];
    newView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:1.0];
    return newView;
}

This basically works, it shows a violet rectangle in my Picker.

But I'd like to be able to load the pickerView item from a NIB file like so...

- (UIView *) pickerView:(UIPickerView *)pickerView
viewForRow:(NSInteger)row
forComponent: (NSInteger)component reusingView:(UIView *)oldView
{

   NSArray * nibs = [[NSBundle mainBundle] loadNibNamed:@"ExpenseItem" owner:self options:nil];
   UIView *newView = [nibs objectAtIndex:0];
   return newView;
}

This yields a blank white screen, which doesn't even show the picker anymore. I can just do it the first way and build out my subviews in code, but there's obviously something going on here that I don't understand. Does anybody know?

Vineel Shah
  • 960
  • 6
  • 14

2 Answers2

2

Put the cell in it's own nib

@interface
    IBOutlet UITableViewCell *cellFactory;


@implementation
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LapCellID"];
    if(nil == cell) {
        [[NSBundle mainBundle] loadNibNamed:@"LapCell" owner:self options:nil];
        cell = [cellFactory retain]; // get the object loadNibNamed has just created into cellFactory
        cellFactory = nil; // make sure this can't be re-used accidentally
    }
zaph
  • 111,848
  • 21
  • 189
  • 228
1

I'd rather create a cell inside a .xib resource as the first item and then refer to it like so:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LapCellID"];
if(!cell) 
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed: cellNibName owner: nil options: nil];
    cell = [nib objectAtIndex: 0];
}

This removes the dependency of having the cell resource require knowledge of the table controller (the cellFactory Outlet) allowing the cell to be re-used in multiple controllers easier.

Leslie Godwin
  • 2,601
  • 26
  • 18