設置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;
            
        }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容