UITableViewCell с галочкой, дублирующие галочки - PullRequest
0 голосов
/ 19 декабря 2011

Пока что при поиске переполнения стека я не нашел ситуацию, похожую на мою. Любая помощь будет принята с благодарностью: я продолжаю следить за тем, чтобы, если я поставлю галочку на Лице А, у Лица H будет такой же флажок, как и у человека около 10. Обычно каждые 10 повторяется галочка.

Вот мой код:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{static NSString *CellIdentifier = @"MyCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

             }

cell.textLabel.text = 

[NSString  stringWithFormat:@"%@ %@", [[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"FirstName"],[[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"LastName"]];
cell.detailTextLabel.text = 

[NSString  stringWithFormat:@"%@", [[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"Address"]];

return cell;

}

В моей выбранной строке для индекса пути у меня есть это:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
cell = [self.tableView cellForRowAtIndexPath: indexPath];

if ([[myArrayOfAddressBooks objectAtIndex:indexPath.row] objectForKey:@"emailSelected"] != @"YES")
{    
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[[myArrayOfAddressBooks objectAtIndex:indexPath.row] setValue:@"YES" forKey:@"emailSelected"];
}
else
{    
    cell.accessoryType = UITableViewCellAccessoryNone;
    [[myArrayOfAddressBooks objectAtIndex:indexPath.row] setValue:@"NO" forKey:@"emailSelected"];
}     

1 Ответ

6 голосов
/ 19 декабря 2011

Это связано с тем, как UITableView «перерабатывает» UITableViewCell в целях эффективности, и с тем, как вы отмечаете свои ячейки, когда они выбраны.

Вам необходимо обновить / установить значение accessoryTypeдля каждой ячейки, которую вы обрабатываете / создаете в tableView:cellForRowAtIndexPath:.Вы корректно обновляете состояние в своей структуре данных myArrayOfAddressBooks, и вам просто нужно использовать эту информацию в tableView:cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    static NSString *CellIdentifier = @"MyCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    NSDictionary *info = [myArrayOfAddressBooks objectAtIndex:indexPath.row];

    cell.textLabel.text = [NSString  stringWithFormat:@"%@ %@", [info objectForKey:@"FirstName"],[info objectForKey:@"LastName"]];
    cell.detailTextLabel.text = [NSString  stringWithFormat:@"%@", [info objectForKey:@"Address"]];

    cell.accessoryType = ([[info objectForKey:@"emailSelected"] isEqualString:@"YES"]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

    return cell;
}

Кроме того, если нет веских причин для сохранения состояния как @"Yes"или @"No" строки, почему бы не сохранить их как [NSNumber numberWithBool:YES] или [NSNumber numberWithBool:NO]?Это упростит вашу логику, когда вы захотите проводить сравнения, вместо того, чтобы постоянно использовать isEqualToString:.

например,

    cell.accessoryType = ([[info objectForKey:@"emailSelected"] boolValue]) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...