DidseleCtrectIndexPath, выбирая множественные аксессуары для ячейки TableView

StackOverflow https://stackoverflow.com/questions/19828171

Вопрос

У меня есть обзор таблицы, содержащий список имен пользователей, которые индексируются в разделах и строк в алфавитном порядке. Когда я нажимаю на один из строк в разделе, правильный пользователь добавляется в массив моих получателей, а галочка - это места в ячейке, кроме их имени. Но следа также отображается рядом с другими именами пользователей, которые не были выбраны и не в массиве получателей. Я попытался переназначить выбранную ячейку с новой индексной дорожкой (см. Код ниже), но не смог заставить ее работать. Он регистрирует правильный путь, но не назначит его. Я использую аналогичный метод для назначения пользователям строк в каждом разделе без проблем, но по какой -то причине аксессуары дают мне проблемы. Я видел некоторые другие темы на переполнении по той же теме, но мысли о том, чтобы прийти к решению для моего случая. какие -нибудь подсказки? ваше здоровье!

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    int row = indexPath.row;
    int section = indexPath.section;
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];

    [tableView deselectRowAtIndexPath:newIndexPath animated:NO];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];

    NSArray *array = [self.sectionsArray objectAtIndex:indexPath.section];
    PFUser *user = [array objectAtIndex:indexPath.row];

    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.recipients addObject:user];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self.recipients removeObject:user];
    }

    [self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (error) {
            NSLog(@"Error %@ %@", error, [error userInfo]);
        }
    }];

А вот CellForroworAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Get the user names from the array associated with the section index in the sections array.
    NSArray *userNamesInSection = (self.sectionsArray)[indexPath.section];

    // Configure the cell with user name.
    UserNameWrapper *userName = userNamesInSection[indexPath.row];
    cell.textLabel.text = userName.user;

    return cell;
}
Это было полезно?

Решение

Как я вижу, вы допустили 2 ошибки в CellForroborAtIndexPath, которые не проверяли, является ли Cell Null, чтобы создать одну и установить AccessyType для ячейки в соответствии со списком получателей.

Вы должны делать это ниже:

NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

PFUser *user = [self getUserAtIndexPath:indexPath];
cell.textLabel.text = user.name;

if ([self.recipients containObject:user]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

return cell;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top