[英]Reusable custom cell
我有一個帶custom cell
的tableView
。 我有可能將一些元素保存到收藏夾中,當發生這種情況時,我想在cell
添加一個星形image
。 我試圖這樣做,但在明星出現后,我有一個問題。 我認為這是因為reusable
cell
但我不知道如何解決它。 我的問題是: stars appear again on the other cells even if the word is not added on favorites.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell=[[dictionaryTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.word.text = self.tableData[indexPath.row];
BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
if (isTheObjectThere==TRUE) {
cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
}
}
return cell;
}
替換以下代碼代替cellForRowAtIndexPath
。 你會得到你想要的輸出。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell=[[dictionaryTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
cell.favImg.hidden = YES;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.word.text = self.tableData[indexPath.row];
BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
if (isTheObjectThere==TRUE) {
cell.favImg.hidden = NO;
cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
}
}
return cell;
}
希望這對你有所幫助。
如果對象不為TRUE
則必須刪除圖像
if (isTheObjectThere==TRUE) {
cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
} else {
cell.favImg.image=nil;
}
是的,你是對的,因為通過帶有標識符的dequeueReusableCell重用你的單元格 -
dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
根據您的要求,您可以在單元格上設置星形圖像,以指示相應單元格上的某些喜歡的元素,如下所示
BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
if (isTheObjectThere==TRUE) {
cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
}
當重新使用任何具有星形圖像的單元格時,如果下一個單元格不是某些喜歡的元素,但是如果它確實有一些喜歡的元素,那么它應該被刪除
要解決此問題,只需使用上面的if語句添加else case
if (isTheObjectThere == TRUE)
cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
else
cell.favImg.image=nil;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.