2012-12-11 57 views
2

我在哪裏設置cellForRowAt中的tableview單元格的backgroundImage ..我該怎麼做?這是我做的,它有點不錯,但我想知道的是,設置背景圖像(cell.backgroundView)的正確方法是在if(cell==nil)或「if」之外的正確位置。UITableViewCell背景視圖/ image

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
    static NSString *cellIdentifier = @"RootViewCellIdentifier"; 

    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; 

     cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]]; 
    } 

    return cell; 
} 
+0

定義 「還挺作品」。此外,如果您已註冊單元格或使用故事板/原型佈局,單元格將永遠不會等於零。 – jrturton

+0

請澄清「有點作品」。你有什麼似乎合理的。 – rmaddy

回答

6

用於做到這一點,但現在我更喜歡willDisplayCell

- (void)tableView:(UITableView *)tableView 
    willDisplayCell:(UITableViewCell *)cell 
    forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    cell.backgroundColor = [UIColor redColor]; 
} 

文件說

表視圖將它使用電池來之前這個消息,其委託畫出一行,從而允許委託人自定義單元格對象,然後顯示。此方法使代表有機會覆蓋表視圖較早設置的基於狀態的屬性,例如選擇和背景顏色。委託返回後,表視圖僅設置alpha和frame屬性,然後僅在滑動或滑出行時對行進行動畫處理。

當使用cellForRowAtIndexPath時,出現了一些奇怪的特殊情況,其中單元格定製並沒有像我想要的那樣完全工作。 willDisplayCell沒有這樣的問題。

-1

爲單元格設置背景視圖的最佳位置是tableView:willDisplayCell:forRowAtIndexPath:方法。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]]; 
} 
+0

這將在每次顯示單元格時創建新的背景視圖。 –

0
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
[cell.imageview setImage:[UIImage imageNamed:@"image1.png"]]; 
    } 
return cell; 

}

0

這種嘗試可能會有所幫助......

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
    static NSString *cellIdentifier = @"RootViewCellIdentifier"; 

    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; 

     UIImageView *backimg = [[UIImageView alloc] init]; 
     backimg.frame = CGRectMake(0, 0, 320, 44); 
     backimg.tag = 20; 
     [cell.contentView addSubview:backimg]; 
    } 
    UIImageView *imag = (UIImageView *)[cell.contentView viewWithTag:20]; 
    [imag setImage:[UIImage imageNamed:@"sky.png"]]; 
    return cell; 
} 
相關問題