UITableView 实现单选 cell

  1. 首先声明一个属性
@property (nonatomic, assign) NSInteger currentIndex;   //当前选中 cell 的索引
  1. 初始化相关数据
- (void)viewDidLoad {
        [super viewDidLoad];
        self.currentIndex = -1;  //初始值为-1,因为 row 不可能小于0
        self.table.delegate = self;
        self.table.dataSource = self;
        self.dataArr = @[@"man", @"woman"];
  }
  1. 实现代理方法
       - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
           static NSString * cellIndentifier = @"cell";
           UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
           if (!cell) {
               cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
           }
           cell.textLabel.text = self.dataArr[indexPath.row];
           if (self.currentIndex == indexPath.row) {   //当前选中的行
               cell.accessoryType = UITableViewCellAccessoryCheckmark;
           }else{
               cell.accessoryType = UITableViewCellAccessoryNone;
           }
           return cell;
       }
       - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
           [tableView deselectRowAtIndexPath:indexPath animated:YES];
           //取出之前选择的cell在数据源中的索引,如果是第一次选择,则self.currentIndex为 -1.
           if (self.currentIndex == indexPath.row) {
               
               /*
                //这段代码的目的是实现再次点击选中的 cell 的时候,取消选择,可根据实际情况选用
               UITableViewCell * currentCell = [tableView cellForRowAtIndexPath:indexPath];
               if (currentCell.accessoryType == UITableViewCellAccessoryNone) {
                   currentCell.accessoryType = UITableViewCellAccessoryCheckmark;
                   self.currentIndex = indexPath.row;
               } else {
                   currentCell.accessoryType = UITableViewCellAccessoryNone;
                   self.currentIndex = -1;
               }
                */
               return;
           }
           //记录之前选择的索引
           NSIndexPath * old = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
           //得到当前cell
           UITableViewCell * newCell = [tableView cellForRowAtIndexPath:indexPath];
           if (newCell.accessoryType == UITableViewCellAccessoryNone) {
               newCell.accessoryType = UITableViewCellAccessoryCheckmark;
               self.currentIndex = indexPath.row;
           }
           //得到上次选择的cell
           UITableViewCell * oldCell = [tableView cellForRowAtIndexPath:old];
           if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
               oldCell.accessoryType = UITableViewCellAccessoryNone;
           }
       }

你可能感兴趣的:(UITableView 实现单选 cell)