UITableview buttons getting highlighted on scroll

后端 未结 1 1001
忘掉有多难
忘掉有多难 2021-01-26 06:10

I have toggle buttons in my tableview cells and I click them on for some cells but when I scroll down, those same buttons are selected for the bottom cells as well even though I

相关标签:
1条回答
  • 2021-01-26 06:59

    You'd have to select or deselect them in cellForRowAt. For example if your cell had a leftButton property and you had a model like this, you could do something like the following:

    @interface Model : NSObject
    
    @property (nonatomic, assign) BOOL selected;
    
    @end
    
    @protocol CustomCellDelegate <NSObject>
    
    - (void)cellActionTapped:(UITableViewCell *)cell;
    
    @end
    
    @interface CustomCell : UITableViewCell
    
    @property (nonatomic, assign) BOOL leftButtonSelected;
    @property (weak, nonatomic, nullable) id<CustomCellDelegate> delegate;
    
    @end
    
    // ModelViewController.h
    @interface ModelViewController : UIViewController<CustomCellDelegate>
    
    @end
    
    // ModelViewController.m
    @interface ViewController () {
        NSArray<Model*>* models;
    }
    
    @end
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
        ((CustomCell *)cell).delegate = self;
        ((CustomCell *)cell).leftButtonSelected = models[indexPath.row].selected;
        return cell;
    }
    
    - (void)cellActionTapped:(UITableViewCell *)cell {
        NSIndexPath *indexPath = [tableView indexPathForCell:cell];
        // Update data source using (maybe) indexPath.row
    }
    
    0 讨论(0)
提交回复
热议问题