设置TableView的某个cell上Button的选中状态(思路及实现)

  • 效果如图所示
选中某个cell.gif
  • 应用场景

    • 选中cell上面的某一个button时其他cell上buttonw
    • 选中这个cell在cell的右端有个标识代表选中
  • 实现思路

    • 记录下当前点击button所在cell的IndexPath.row
    • 在数据源方法中判断记录下的IndexPath.row是否等于当前的IndexPath.row
    • 如果相等设置cell上button为选中状态即可
  • 代码如下

    • 直接刷新Tableview
- (void)selectedBtnClick:(UIButton *)button
{
    // 通过button计算出其所在的cell
    UITableViewCell * cell = (UITableViewCell *)[[button superview] superview];
    NSIndexPath * path = [self.hsTabbleView indexPathForCell:cell];

    // 记录下当前的IndexPath.row
    self.indexPathRow = path.row;
    
    // 刷新数据源方法
    [self.hsTabbleView reloadData];
    
}
  • 仅刷新Button所在Section的cell(更节省资源)
- (void)selectedBtnClick:(UIButton *)button
{
    // 通过button计算出其所在的Cell
    UITableViewCell * cell = (UITableViewCell *)[[button superview] superview];
    NSIndexPath * path = [self.hsTabbleView indexPathForCell:cell];

    // 记录下当前的IndexPath.row
    self.indexPathRow = path.row;
    
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:path.section];
    // 刷新数据源方法
    [self.hsTabbleView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    
}
  • 数据源方法中
if (self.indexPathRow == indexPath.row) {
            // 如果是当前cell
            cell.supportBtn.selected = YES;
            
        }else{
            
            cell.supportBtn.selected = NO;
            
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容