定义两个属性
@property (weak, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;
- (void)viewDidLoad {
[super viewDidLoad];
self.dataArray = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];
//创建tableview
[self createTableView];
NSLog(@"%@", self.dataArray);
}
- (void)createTableView{
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
tableView.editing = YES;
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
self.tableView = tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.textLabel.text = self.dataArray[indexPath.row];
return cell;
}
#pragma mark --删除cell
//编辑的风格
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//返回删除效果
return UITableViewCellEditingStyleDelete;
}
//点击左边删除按钮时 显示的右边删除button的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
return @"删除";
}
//提交编辑效果
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
//当你删除时
NSLog(@"第%lu行被删除了",indexPath.row);
//先将数据源中的数据删除了
[self.dataArray removeObjectAtIndex:indexPath.row];
//以动画的形式删除指定的cell
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#pragma mark --移动cell
//是否移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
//指定代理方法 可以移动cell
return YES;
}
//移动代理方法
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
NSLog(@"移动");
//取出要移动的元素
NSString *item = [self.dataArray objectAtIndex:sourceIndexPath.row];
//删除原有的元素
[self.dataArray removeObjectAtIndex:sourceIndexPath.row];
//将源位置数据插入目的位置
[self.dataArray insertObject:item atIndex:destinationIndexPath.row];
}