我是iOS新手,在用戶選擇單元格時遇到了添加/刪除單元accessoryTypeCheckmark的問題。我在UITableView中有一個好友列表,用戶應該能夠選擇多個好友,並在他們旁邊顯示覆選標記。如果用戶點擊已經被選中的朋友,對勾應該消失。我跟蹤一個名爲「friends_selected」的NSMutableArray中選中的朋友。無法更新didSelectRowAtIndexPath中的cellaccessory
我設置了cellForRowAtIndex路徑來檢查friends_selected數組是否包含用戶名,如果是這樣,請添加複選標記。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
FriendsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.usernameID.text = [self.friends_username objectAtIndex:indexPath.row];
if ([self.friends_selected containsObject:cell.usernameID.text]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
以我didSelectRowAtIndexPath方法我添加或移除該friends_selected陣列的用戶名和重新加載的表數據。
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
FriendsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.usernameID.text = [self.friends_username objectAtIndex:indexPath.row];
if ([self.friends_selected containsObject:cell.usernameID.text]) {
[self.friends_selected removeObject:cell.usernameID.text];
}
else {
[self.friends_selected addObject:cell.usernameID.text];
}
[tableView reloadData];
}
此時friends_selected數組正在更新,用戶名已被選擇或取消選擇。沒有複選標記出現,但單元格將在選中時變亮,並且即使未選中也將保持高亮顯示。任何幫助都會很棒,我一直都在這個問題上陷入困境,這似乎是一個簡單的解決方案。
謝謝你是這個問題!知道這是簡單的事情。如果你這樣做,而不是類型轉換單元格,你會得到一個錯誤,所以應該是:FriendsListCell * cell =(FriendsListCell *)[tableView cellForRowAtIndexPath:indexPath]; –
我沒有忘記演員。我更新了答案。 – rmaddy