實現(xiàn) tableView 中 cell 的單行選中
- 首先自己創(chuàng)建一個列表,實現(xiàn)單選,先定義一個變量記錄每次點擊的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];
}
- 系統(tǒng)自帶的選中效果
Snip20170315_2.png
- 實現(xiàn)代碼
- (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);
}
- 2.自定義效果
Snip20170315_1.png
- 實現(xiàn)代碼
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 創(chuàng)建 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;
}
}