2012-06-21 20 views
0

我一直設定我的UITableViewCell的的cellForRowAtIndexPath調用內部的背景下,這樣的:設置UITableViewCell的背景視圖 - 哪種方式更好?

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:simple]; 

if (cell == nil) 
{ 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 

    for (id findCell in nib) 
    { 
     if ([findCell isKindOfClass: [CustomCell class]]) 
     { 
      cell = findCell; 
     }  
    } 

    UIView *cellBackView = [[UIView alloc] initWithFrame:CGRectZero]; 
    UIView *cellSelectedBackView = [[UIView alloc] initWithFrame:CGRectZero]; 

    if (UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM()) { 

     cellBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_shadows_ipad_light.png"]]; 
     cellSelectedBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"blue_cell.png"]]; 
    }else { 
     cellBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_shadows.png"]]; 
     cellSelectedBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"blue_cell.png"]]; 
    } 

    cell.backgroundView = cellBackView; 
    cell.selectedBackgroundView = cellSelectedBackView; 

現在我發現,還有另一種方式來實現這一目標,這是設置該委託裏面的背景意見:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ 
    // load the background image and set it as the background color as above 
} 

而自iOS5以來,你只需要在tableView中註冊nib,所以我不需要循環尋找類nib。所以,在viewDidLoad中:

[self.tableView registerNib:[UINib nibWithNibName: @"CustomCellSplit" bundle:nil] forCellReuseIdentifier: @"CustomCellId"]; 

所以這個作品,它更簡單,它是裝載電池的筆尖和設置背景圖的蘋果推薦的方式。但是,我發現這個tableView:willDisplayCell:forRowAtIndexPath會在您滾動列表時爲每一行調用。用我之前加載背景視圖的方式,它只會在單元格創建時設置backgroundView(最多8或10次)。

因此,這種新的方式聽起來像加載單元格和設置backgroundViews的性能較差的方式。這是正確的假設,還是我在這裏錯過了一些東西?

回答

1

原來這很簡單。您只需在筆尖中添加一個子視圖並將其連接到UITableViewCell中的selectedBackgroundView插座。

http://cl.ly/image/322L2k3j2U1Aconnecting selectedBackgroundView outlet from nib

瞧。

iOS5足夠智能,可以在運行時從單元的contentView中移除backgroundView。不需要使用tableView:willDisplayCell函數。