我使用包含2個部分的UITableview創建控制器。在第二部分中,我有一列用戶列表,當我點擊特定行時,我想向列表中的用戶添加複選標記。我遇到了一個問題,點擊用戶並將單元格滾動出頁面後,單元格將返回「名稱」字段BLANK(請參見下面的截圖)。我知道這與細胞被重複使用的方式有關,但我無法解決問題。我的代碼發佈在下面。有任何建議嗎?目標C:在滾動出屏幕(和返回)後單元格文本消失
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* ShareOnCellIdentifier = @"ShareOnholderCell";
static NSString* WhoShouldAnswerCellIdentifier = @"WhoShouldAnswerCell";
int row = [indexPath row];
User *user = [self.friendsToShareWithArray objectAtIndex:row];
if (indexPath.section == 0)
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ShareOnCellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ShareOnCellIdentifier];
}
cell.textLabel.text = [self.shareOnArray objectAtIndex:indexPath.row];
return cell;
}
else
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:WhoShouldAnswerCellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:WhoShouldAnswerCellIdentifier];
}
cell.textLabel.text = user.nickname;
if (user.isSelected)
{
cell.selectionStyle = UITableViewCellAccessoryCheckmark;
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
User *user = [self.friendsToShareWithArray objectAtIndex:indexPath.row];
if (indexPath.section == 1)
{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
user.isSelected = NO;
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
user.isSelected = YES;
}
}
}
編輯:我如何創建我的用戶對象
User *user1 = [[User alloc]init];
user1.nickname = @"Dionis";
user1.uid = @"1";
user1.isSelected = NO;
by cell.selectionStyle = UITableViewCellAccessoryCheckmark;'你的意思是'cell.accessoryType = UITableViewCellAccessoryCheckmark;'對嗎? – 2011-06-17 01:19:41
是的,這是對的,愚蠢的錯誤從我身上。感謝您指出這一點 – Zhen 2011-06-17 01:38:32
不是你的答案,但你泄漏細胞。每當你分配/初始化一個新單元時,你也需要自動釋放它。否則,您創建的每個表格單元格都會永遠存在 – 2011-06-17 01:46:12