表格的修改

来源:互联网 发布:c语言大小写单词转换 编辑:程序博客网 时间:2024/05/19 21:03

表格的修改

一、懒加载UITableView
- (UITableView*)tableView
{
   
if (_tableView== nil) {
       
_tableView = [[UITableViewalloc]initWithFrame:self.view.boundsstyle:UITableViewStylePlain];
       
       
_tableView.dataSource= self;
       
_tableView.delegate= self;
       
        [
self.viewaddSubview:_tableView];
    }
   
return _tableView;
}
注意:
手动实现dataSource和delegate的代理方法

二、在viewDidLoad方法里面
//开始编辑,一旦editing == YES就默认开启删除模式
 self.tableView.editing= YES;

//只要实现了此方法,就能够支持手势拖拽删除了,删除需要自己干!
/**
 UITableViewCellEditingStyleNone,
 UITableViewCellEditingStyleDelete,    
删除
 UITableViewCellEditingStyleInsert     
添加
 */

三、实现代理的其他方法
- (
void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
   
if (editingStyle ==UITableViewCellEditingStyleDelete) {
       
// 1. 删除self.dataListindexPath对应的数据
        [
self.dataListremoveObjectAtIndex:indexPath.row];

       
// 2. 刷新表格(重新加载数据)
       
// deleteRowsAtIndexPaths让表格控件动画删除指定的行
        [
self.tableViewdeleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationMiddle];
    }
else if (editingStyle ==UITableViewCellEditingStyleInsert) {
       
// 1. 向数组添加数据
        [
self.dataListinsertObject:@"王小二"atIndex:indexPath.row +1];
       
// 2. 刷新表格
       
// insertRowsAtIndexPaths让表格控件动画在指定indexPath添加指定行
       
// 新建一个indexPath
       
NSIndexPath *path = [NSIndexPathindexPathForRow:indexPath.row+ 1 inSection:indexPath.section];
        [
self.tableViewinsertRowsAtIndexPaths:@[path]withRowAnimation:UITableViewRowAnimationMiddle];
    }
}

//只要实现此方法,就可以显示拖动控件
- (
void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
     // 交换索引,将数据源索引和目标索引交换
//    [self.dataList exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];

   
// 1. 将源从数组中取出
   
id source =self.dataList[sourceIndexPath.row];
   
// 2. 将源从数组中删除
    [
self.dataListremoveObjectAtIndex:sourceIndexPath.row];
   
NSLog(@"%@",self.dataList);
   
   
// 3. 将源插入到数组中的目标位置
    [
self.dataListinsertObject:sourceatIndex:destinationIndexPath.row];
   
   
NSLog(@"%@",self.dataList);
}

#pragma mark -代理方法
//返回编辑样式,如果没有实现此方法,默认都是删除
- (
UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{

   
return UITableViewCellEditingStyleInsert;
}
0 0
原创粉丝点击