How can I get index path of cell on switch change event in section based table view

前端 未结 3 1375
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 19:47

I have custom cell having switch in few cells at right side. what I want is to store value of specific cell on switch change event. Table view has number sections so I can\'

3条回答
  •  温柔的废话
    2020-12-03 20:26

    In your custom cell add properties which help you identify the information the cell represents. Index path, indexes for your data model etc...

    Then add a block property to the cell which you can call to tell a UITableView or any other piece of code when a cell switch changes. e.g.

    @property (nonatomic,copy) void (^onSwitchChange)(UITableViewCell *cell);
    

    Inside your custom cell code, add an action handler for the UISwitch. When it fires, call self.onSwitchChange(self) which will notify the code which registered an onSwitchChange block that a switch has changed and on which cell.

    In your table view when you create the cell, set the onSwitchChange block as follows:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath
    {
      
    
      YourUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:yourCellIdentifier forIndexPath:indexPath];
      cell.onSwitchChange=^(UITableViewCell *cellAffected){
        // Add code to deal with the swicth switch using properties of cellAffected
        ... Your handler code here ...
      }];
    
      
    }
    

    This lets you handle all the changes in the table view controller. Hope this helps.

提交回复
热议问题