如何一次只为一个单元格显示UITableViewCell的accessoryType属性?

时间:2015-05-10 21:58:39

标签: ios objective-c uitableview

我有一个表格视图,我想在选定的单元格中显示一个复选标记accessoryType,但现在我所拥有的是所选单元格的复选标记...有人可以帮我修复此方法?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * key = [self.settingsArray objectAtIndex:indexPath.row];
    NSString * key2 = [self.soundsArray objectAtIndex:indexPath.row];

    if (tableView.tag != 313) {
        if([key isEqual:@"Reminder Sound"]){
            [self reminderSoundPressed];
        } else if([key isEqual:@"Sound"]){

        }
    }

    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

    //setting the reminder
     if (tableView.tag == 313) {

         if ([key2 isEqual:@"Sound 1"]) {
             [self.delegate setReminderSound:@"reminderSound1.wav"];
             newCell.accessoryType = UITableViewCellAccessoryCheckmark;

         }else if ([key2 isEqual:@"Sound 2"]) {
             [self.delegate setReminderSound:@"reminderSound2.wav"];
             newCell.accessoryType = UITableViewCellAccessoryCheckmark;

         }else if ([key2 isEqual:@"Sound 3"]) {
             [self.delegate setReminderSound:@"reminderSound3.wav"];
             newCell.accessoryType = UITableViewCellAccessoryCheckmark;
         }
     }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案是实现委托功能 - tableView:didDeselectRowAtIndexPath:并删除其中的复选框。

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

更优雅的解决方案是创建自定义UITableViewCell类并覆盖setSelected函数。

- (void)setSelected:(BOOL)selected
           animated:(BOOL)animated
{
      [super setSelected:selected animated:animated];
      self.accessoryType = selected ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; 
}