月圆之夜,紫禁之巅,一剑西来,天外飞仙。

0%

iOS学习笔记--tableView多选实现

1
本文介绍使用tableView自带的方法来实现多选功能。
1
2
3
@property(nonatomic,strong)UITableView *  tmptabelView;
@property(nonatomic,strong)NSMutableArray * saveArray;
@property(nonatomic,strong)NSMutableArray * array;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
-(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]];

}
}

}