2009-08-11 17 views
0

我想弄清楚如何實現自定義的UITableViewCell作爲筆尖...我知道如何UITableView的工作原理,但與界面生成器NIB實現自定義單元格增加了複雜性......但有助於靈活性....我的問題是這樣的:自定義UITableViewCell筆尖是否需要自定義OBJ-C類作爲文件所有者?

在Interface Builder設計自定義單元格後,我們需要創建要指定爲文件所有者的OBJ-C自定義類就像我們在ViewControlers辦?

回答

1

您可以使用自定義類作爲文件的所有者,但您不必。我將向您展示兩種從NIB加載表格單元的技術,一種使用文件所有者,另一種不使用。

不使用文件的所有者,這裏是從NIB加載表格單元格的方式:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"]; 
    if (!myCell) { 
     NSBundle *bundle = [NSBundle mainBundle]; 
     NSArray *topLevelObjects = [bundle loadNibNamed:@"MyNib" owner:nil options:nil]; 
     myCell = [topLevelObjects lastObject]; 
    } 
    /* setup my cell */ 
    return myCell; 
} 

上面的代碼是脆弱的,因爲在未來,如果你修改XIB有更多的頂級對象,這段代碼可能會通過從「[topLevelObjects lastObject]」獲取錯誤的對象而失敗。儘管如此,它並不脆弱,所以這種技術很好用。

要多一點明確的和穩健的,您可以使用文件的所有者和出口,而不是使用頂級對象。這裏有一個例子:

@interface MyTableViewDataSource : NSObject { 
    UITableViewCell *loadedCell; 
} 
@property (retain) UITableViewCell *loadedCell; 
@end 

@implementation MyTableViewDataSource 

@synthesize loadedCell; 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"]; 
    if (!myCell) { 
     [[NSBundle mainBundle] loadNibNamed:@"MyNib" owner:self options:nil]; 
     myCell = [[[self loadedCell] retain] autorelease]; 
     [self setLoadedCell:nil]; 
    } 
    /* setup my cell */ 
    return myCell; 
} 
@end 
+0

我使用的是第一種方法,因爲它似乎被許多開發中使用...但是,我更喜歡第二個,因爲它最終給了我什麼,我們可以更多的控制在自定義類中放置更多的init代碼....更多面向對象的... – JFMartin 2009-08-18 00:29:32

相關問題