//创建私有模型
@interface Model : NSObject
@property (nonatomic, assign)BOOL isSelect;
@property (nonatomic, copy)NSString * text;
@end
@interface RootViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)NSMutableArray * dataArr;
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
self.dataArr = [@[]mutableCopy];
//创建数据源
for (int i = 0; i < 108; i++) {
Model * model = [Model new];
model.isSelect = NO;
model.text = [NSString stringWithFormat:@"%d",i];
[self.dataArr addObject:model];
}
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArr.count;
}
//cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
Model * m = self.dataArr[indexPath.row];
cell.textLabel.text =m.text;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Model * model = self.dataArr[indexPath.row];
//根据数据源,判断cell 的颜色
if (model.isSelect) {
cell.backgroundColor = [UIColor greenColor];
}else{
cell.backgroundColor = [UIColor whiteColor];
}
return cell;
}
//点击cell触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Model * m = self.dataArr[indexPath.row];
m.isSelect = !m.isSelect;
//刷新一行
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
//删除方法
- (IBAction)delete:(UIButton *)sender {
//创建数组替身
NSArray * tempArr = [NSArray arrayWithArray:self.dataArr];
NSMutableArray * objectArr= [@[]mutableCopy];
NSMutableArray * cellArr = [@[]mutableCopy];
for (Model * m in tempArr) {
if (m.isSelect) {
[objectArr addObject:m];
[cellArr addObject:[NSIndexPath indexPathForRow:[tempArr indexOfObject:m] inSection:0]];
}
}
[self.dataArr removeObjectsInArray:objectArr];
[self.tableView deleteRowsAtIndexPaths:cellArr withRowAnimation:UITableViewRowAnimationTop];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
@implementation Model
@end