1.功能实现:试下在UITableView中添加手删除数据
(一).创建storyboard视图
(二).在ViewController接口中实现UITableView代理方法<UITableViewDelegate,UITableViewDataSource>.
(三).连接storyboard中按钮属性和方法
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
//删除
- (IBAction)deleteBut:(id)sender;
//添加
- (IBAction)addBut:(id)sender;
//数据集合
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
(四).在ViewController.m加载时准备数据源
- (void)viewDidLoad {
[super viewDidLoad];
//准备数据
_array = [NSMutableArray alloc].init;
for (NSInteger i=0; i<50; i++) {
NSString *str = [NSString stringWithFormat:@"书籍-%03d",i];
[_array addObject:str];
}
NSLog(@"%@",_array);
}
(五).实现UITableViewDataSource方法- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section,设置列表一共多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _array.count;
}
(六).初始化UITablveViewCell数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mylist"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"mylist"];
}
//设置数据
[[cell textLabel] setText:_array[indexPath.row]];
[[cell detailTextLabel] setText:@"数据详情"];
return cell;
}
(七).点击删除按钮进入编辑模式
#pragma make-删除事件
- (IBAction)deleteBut:(id)sender {
[_tableView setTag:UITableViewCellEditingStyleDelete];
BOOL is = [_tableView isEditing];
[_tableView setEditing:!is animated:YES];
}
(八).提交删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if(editingStyle == UITableViewCellEditingStyleDelete) {
//提交删除
NSLog(@"删除");
//移除数据
[_array removeObjectAtIndex:indexPath.row];
//更新数据
[_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
} else if(editingStyle == UITableViewCellEditingStyleInsert) {
//提交添加
NSLog(@"添加");
NSInteger index = indexPath.row;
[_array insertObject:@"新加数据" atIndex:index + 1];
NSIndexPath *newPath = [NSIndexPath indexPathForRow:index + 1 inSection:0];
[_tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationTop];
}
NSLog(@"%@",_array);
}
注意,UITableView默认编辑模式为删除,必须实现- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath方法设置编辑模式风格
#pragma mark-设置编辑模式风格
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return _tableView.tag;
}
#pragma make-添加事件
- (IBAction)addBut:(id)sender {
[_tableView setTag:UITableViewCellEditingStyleInsert];
BOOL is = [_tableView isEditing];
[_tableView setEditing:!is animated:YES];
}