從您的問題中不清楚您是否意識到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"
標識符的課程。
你在哪裏調用該類方法? – jaredsinclair
從viewDidLoad。我只是試圖從viewWillAppear現在起作用。你可以寫出答案,然後我將其標記爲正確。謝謝!如果你能解釋爲什麼它只能在viewWillAppear中工作,那將不勝感激。 – guptron