2012-05-16 4 views
1

Я хочу сделать типичную ситуацию: когда пользователь выбирает любую ячейку, ее аксессуарType поворачивается в галочку. Только аксессуар типа One cell может быть галочкой. И затем я хочу сохранить в NSUserDefaults indexPath.row, поэтому мое приложение сможет узнать, какой пользователь ячейки выбран и внести некоторые изменения в параметры. Так что я написал этот неправильный код:Логика для UITableViewCellAccessoryCheckmark

didSelectRowAtIndexPath

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

    if(self.checkedIndexPath) 
    { 
     UITableViewCell* uncheckCell = [tableView 
             cellForRowAtIndexPath:self.checkedIndexPath]; 
     uncheckCell.accessoryType = UITableViewCellAccessoryNone; 
    } 
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 

    self.checkedIndexPath = indexPath; 

    [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:self.checkedIndexPath.row]forKey:@"indexpathrow" ]; 
} 

cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Part of code from cellForRowAtIndexPath 

    if(indexPath.row == [[[NSUserDefaults standardUserDefaults]objectForKey:@"indexpathrow"]intValue ]) 
    { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 
    else 
    { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

     return cell; 
} 

Однако, этот код работает плохо. Когда вы открываете UITableView, в таблице есть уже выбранная ячейка, и когда вы нажимаете другую, есть две ячейки checkmarked ... Как я могу улучшить свой код или изменить его в целом? Какие-либо предложения ? Спасибо!

ответ

6

Попробуйте этот код:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // checkedIndexPath is NSIndexPath 
    NSIndexPath *previousSelection = self.checkedIndexPath; 
    NSArray *array = nil; 
    if (nil != previousSelection) { 
     array = [NSArray arrayWithObjects:previousSelection, indexPath, nil]; 
    } else { 
     array = [NSArray arrayWithObject:indexPath]; 
    } 

    self.checkedIndexPath = indexPath; 

    [tableView reloadRowsAtIndexPaths:array withRowAnimation: UITableViewRowAnimationNone]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Part of code from cellForRowAtIndexPath 
    NSString *cellID = @"CellID"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 
    if (nil == cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; 
     [cell autorelease]; 
    } 

// some code for initializing cell content 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    if(self.checkedIndexPath != nil && indexPath.row == self.checkedIndexPath.row) 
    { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } else { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

    return cell; 
} 
+0

Спасибо! Вопрос: Кажется, что метод метода метода willSelectRowAtIndexPath не является void, а NSIndexPath, поэтому он просит меня вернуть NSIndexPath. Что я должен вернуть? Благодаря ! – SmartTree

+0

@SmartTree Из документов: объект-указатель, который подтверждает или изменяет выбранную строку. Верните объект NSIndexPath, отличный от indexPath, если вы хотите, чтобы была выбрана другая ячейка. Верните нуль, если вы не хотите, чтобы строка была выбрана. – tux91

+0

@SmartTree, я обновил код-фрагмент для правильного возврата в метод willSelect ... – Denis

Смежные вопросы