2009-08-24 55 views
1

我想在我的UIPicker中創建一個相當複雜的行。所有我見過從頭開始創建一個視圖,像這樣的例子中...從UIB在UIPickerView中加載一行viewForRow

- (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; 
} 

這基本上工作,它是用我自己選擇器一個紫色的矩形。

但我希望能夠從像這樣一個NIB文件加載pickerView項目...

- (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; 
} 

這將產生一個空白屏幕,它甚至不顯示機械手了。我可以用第一種方法做到這一點,並在代碼中構建我的子視圖,但顯然這裏有一些我不明白的事情。有人知道嗎?

回答

2

把細胞在它自己的筆尖

@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 
    } 
1

我寧願創建的.xib資源中的單元格作爲第一個項目,然後引用它,像這樣:

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

這消除了使單元資源需要表格控制器(cellFactory Outlet)的知識的依賴性,從而允許單元更容易地在多個控制器中重新使用。