2013-07-13 42 views
0

對於我的普通樣式表格視圖,這適用於正常的樣式,但不適用於我的分組樣式。我試圖自定義單元格在被選中時的樣子。在分組的UITableView中爲選定的UITableViewCell設置背景

這裏是我的代碼:

+ (void)customizeBackgroundForSelectedCell:(UITableViewCell *)cell { 
    UIImage *image = [UIImage imageNamed:@"ipad-list-item-selected.png"]; 
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
    cell.selectedBackgroundView = imageView; 
} 

我已經驗證了正確的電池確實正在傳遞到這個函數。爲了完成這項工作,我需要做哪些不同的工作?

+0

你在哪裏調用該類方法? – jaredsinclair

+0

從viewDidLoad。我只是試圖從viewWillAppear現在起作用。你可以寫出答案,然後我將其標記爲正確。謝謝!如果你能解釋爲什麼它只能在viewWillAppear中工作,那將不勝感激。 – guptron

回答

1

從您的問題中不清楚您是否意識到tableViewCell會根據其選擇狀態自動管理顯示/隱藏它的selectedBackgroundView。除了viewWillAppear之外,還有更好的地方可以使用這種方法。其中之一是在最初創建tableViewCells的時間,即:

- (UITableViewCell *)tableView:(UITV*)tv cellForRowAtIP:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = nil; 
    cell = [tv dequeueCellWithIdentifier:@"SomeIdentifier"]; 
    if (cell == nil) { 
     cell = /* alloc init the cell with the right reuse identifier*/; 
     [SomeClass customizeBackgroundForSelectedCell:cell]; 
    } 
    return cell; 
} 

您只需要在該單元的壽命設置selectedBackgroundView屬性一次。該單元將適當地管理顯示/隱藏它。

另外,清潔,方法是子類的UITableViewCell,並在子類.m文件,覆蓋:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
    self = [super initWithBla....]; 
    if (self) { 
     UIImageView *selectedBGImageView = /* create your selected image view */; 
     self.selectedBackgroundView = selectedBGImageView; 
    } 
    return self; 
} 

從此你的電池應該顯示它的自定義選擇的背景,沒有任何進一步的修改。它只是工作。

此外,這種方法效果更好,使用以下的UITableView方法viewDidLoad:與表視圖登記表視圖細胞類的現行推薦的做法:

- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier 

你會在你的表視圖控制器的使用這個方法viewDidLoad方法,讓你的表格視圖單元格離隊實現更短,更易於閱讀:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self.tableView registerClass:[SomeClass class] 
      forCellReuseIdentifier:@"Blah"]; 
} 

- (UITableViewCell *)tableView:(UITV*)tv cellForRowAtIP:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = nil; 
    cell = [tableView dequeueReusableCellWithIdentifier:@"Blah" 
              forIndexPath:indexPath]; 
    /* set your cell properties */ 
    return cell; 
} 

這種方法保證,只要返回一個單元爲y您已經註冊了@"Blah"標識符的課程。

相關問題