本文介绍使用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]];
}
}
}