实现 tableView 中 cell 的单行选中
- 首先自己创建一个列表,实现单选,先定义一个变量记录每次点击的cell的indexPath:
- 先说下 tableView 默认选中行
// 默认选中行
NSIndexPath *firstPath = [NSIndexPath indexPathForRow:selectRow inSection:0];
[self.tableView selectRowAtIndexPath:firstPath animated:YES scrollPosition:UITableViewScrollPositionNone];
if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
[self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:firstPath];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *leftCell = @"ordeDetailCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCell];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftCell];
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd行%zd列", indexPath.section, indexPath.row];
// 当上下拉动的时候,因为cell的复用性,我们需要重新判断一下哪一行是打钩的
if (_selIndex == indexPath) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//之前选中的,取消选择
UITableViewCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
celled.accessoryType = UITableViewCellAccessoryNone;
//记录当前选中的位置索引
_selIndex = indexPath;
//当前选择的打勾
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView reloadData];
NSLog(@"old : %zd行%zd列 new : %zd行%zd列", _selIndex.section, _selIndex.row, indexPath.section, indexPath.row);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 创建 tableView
............
UIImageView *ima = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-successed"]];
[ima sizeToFit];
CGFloat width = ima.bounds.size.width;
CGFloat height = ima.bounds.size.height;
[cell.contentView addSubview:ima];
[ima mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(cell.contentView);
make.right.equalTo(cell.contentView.right).offset(-2*SPCommonMargin);
make.width.equalTo(width);
make.height.equalTo(height);
}];
[self.imageArray addObject:ima];
ima.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%zd个 = old : %zd行%zd列 new : %zd行%zd列", self.imageArray.count, _selIndex.section, _selIndex.row, indexPath.section, indexPath.row);
if (self.imageArray.count > 0) {
UIImageView *sender = self.imageArray[_selIndex.row];
sender.hidden = YES;
_selIndex = indexPath;
UIImageView *newSender = self.imageArray[indexPath.row];
newSender.hidden = NO;
}
}