iOS學習筆記--tableView多選實現
阿新 • • 發佈:2019-01-26
本文介紹使用tableView自帶的方法來實現多選功能。
@property(nonatomic,strong)UITableView * tmptabelView;
@property(nonatomic,strong)NSMutableArray * saveArray;
@property(nonatomic,strong)NSMutableArray * array;
self.array = [NSMutableArray arrayWithObjects:@"普通話",@"英語",@"法語",@"俄語",@"日語",@"韓語",@"德語",@"西班牙語",@"泰語",@"小語種" ,nil];
self.saveArray = [NSMutableArray array];
self.tmptabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 300, 400)];
[self.tmptabelView setBackgroundColor:[UIColor whiteColor]];
[self.tmptabelView setDelegate:self];
[self.tmptabelView setDataSource:self];
self.tmptabelView .editing = YES;
self.tmptabelView.allowsMultipleSelectionDuringEditing = YES;
[self.view addSubview:self.tmptabelView];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * ID = @"ID";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];
}
[cell.textLabel setText:[NSString stringWithFormat:@"%@",self.array[indexPath.row]]];
cell.selectedBackgroundView = [[UIView alloc] init];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//將選中的元素儲存
[self.saveArray addObject:self.array[indexPath.row]];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
if (self.array.count > indexPath.row)
{
//將選中的元素移除
if (self.saveArray.count > 0)
{
[self.saveArray removeObject:self.array[indexPath.row]];
}
}
}