Snail—UI学习之表视图TableView多行删除

这次实现的功能是多行cell进行删除

代码是在上一次的基础上进行修改的 有的代码删除重写 有的方法只是加了一些逻辑判断

//
//  WJJRootViewController.m
//  blog_UITableView
//
//  Created by Snail on 15-7-30.
//  Copyright (c) 2015年 Snail. All rights reserved.
//

#import "WJJRootViewController.h"

@interface WJJRootViewController (){
    //数据源 存放数据
    NSMutableArray * _dataArray;
    //这就是我们的tableView
    UITableView * _tableView;
    //页面控制器
    UIPageControl * _pageControl;
    
   <span style="background-color: rgb(204, 204, 204);"> //搜索Bar
    UISearchBar * _searchBar;
    //搜索控制器
    UISearchDisplayController * _searchDC;
    //存储搜索出来的数据 
    NSMutableArray * _searchResultDataArray;
    
    //广告栏的滚动视图
    UIScrollView * _scrollView;</span>
}

@end

@implementation WJJRootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title = @"2";
    //模拟得到数据
    [self createDataSources];
    //创建tableView
    [self createTableView];
    //创建一个BarButton 用来编辑每个cell的
    [self createBarButtonItem];
    
    <span style="background-color: rgb(204, 204, 204);">[self createSearch];</span>
}


<span style="background-color: rgb(204, 204, 204);">- (void)createSearch{
    
    //开始实例化
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    //把搜索条加到导航栏上
    self.navigationItem.titleView = _searchBar;
    //第一个参数:searchBar  第二个参数:展示在哪个controller上
    _searchDC = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchDC.searchResultsDelegate = self;
    _searchDC.searchResultsDataSource = self;
    //如果 搜索条加到导航栏上 下面这句代码必须执行
    _searchDC.displaysSearchBarInNavigationBar = YES;
}
</span>
//得到数据方法的实现 就是在数组中添加20个字符串对象
- (void)createDataSources{
    _dataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 20; i++) {
        NSString * tempStr = [NSString stringWithFormat:@"第%d行",i];
        [_dataArray addObject:tempStr];
    }
}

//创建一个tableView
- (void)createTableView{
    
    /*
     UITableViewStylePlain    不分组的table
     UITableViewStyleGrouped  分组的tableView
     */
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)
                                              style:UITableViewStylePlain];
    //在写完tableView后 一定要把下面这两句写上 代理和数据源都是self
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    
    //创建一个背景视图
    UIView * backgroudView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
    //创建一个滚动视图
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
    //设置滚动视图的实际大小
    _scrollView.contentSize = CGSizeMake(4 * 320, 150);
    //偏移量
    _scrollView.contentOffset = CGPointZero;
    //是否分页
    _scrollView.pagingEnabled = YES;
    //水平的滚动栏隐藏
    _scrollView.showsHorizontalScrollIndicator = NO;
    //设置代理
    _scrollView.delegate = self;
    //没有那种图片到头了的橡皮筋效果
    _scrollView.bounces = NO;
    //加四张图片放到scrollView上面
    for (int i = 0; i < 4; i++) {
        UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(i * 320, 0, 320, 150)];
        [imageV setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image%d.png",i]]];
        [_scrollView addSubview:imageV];
    }
    UIImageView * lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(4 * 320, 0, 320, 150)];
    [lastImageView setImage:[UIImage imageNamed:@"image0.png"]];
    [_scrollView addSubview:lastImageView];
    [NSTimer scheduledTimerWithTimeInterval:3.1 target:self selector:@selector(scroll:) userInfo:nil repeats:YES];
    
    
    //初始化页面控制器  总页数是4  初始页面是0
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 130, 320, 20)];
    _pageControl.numberOfPages = 4;
    _pageControl.currentPage = 0;
    
    //把滚动视图放到背景视图上
    [backgroudView addSubview:_scrollView];
    //把分页控制器方到背景视图上
    [backgroudView addSubview:_pageControl];
    
    //然后把我们创建的背景视图方在tableView的头视图的位置
    _tableView.tableHeaderView = backgroudView;
    
}

<span style="background-color: rgb(204, 204, 204);">//让上面的广告栏自动滑动
- (void)scroll:(NSTimer *)timer{
    
    CGPoint point = _scrollView.contentOffset;
    point.x += 320;
    [UIView animateWithDuration:1 animations:^{
        _scrollView.contentOffset = point;
    } completion:^(BOOL finished) {
        if (_scrollView.contentOffset.x > 3 * 320) {
            _scrollView.contentOffset = CGPointZero;
        }
        NSInteger page = _scrollView.contentOffset.x / 320;
        _pageControl.currentPage = page;
    }];
}</span>
- (void)createBarButtonItem{
    
    //创建一个按钮 点击后使得tableView处于编辑状态
    UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(0, 0, 50, 30);
    [rightButton setTitle:@"edit" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(editTableView)
          forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc]
                                            initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
<span style="background-color: rgb(204, 204, 204);">    //删除按钮
   UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 50, 30);
    [leftButton setTitle:@"delete" forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(deleteAllData)
          forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarButtonItem = [[UIBarButtonItem alloc]
                                            initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;

    
}
</span>

#warning 关于多行删除的操作

<span style="background-color: rgb(204, 204, 204);">- (void)deleteAllData{
    
    //系统会把所选中的indexPath.row 装到一个数组里面
    NSMutableArray * array = [[NSMutableArray alloc]
                              initWithArray:[_tableView indexPathsForSelectedRows]];
    //对这个杂乱无序的数组 排序
    [array sortUsingSelector:@selector(compare:)];
    
    //遍历数组 把每个index取出来 然后再_dataArray里面对应的元素删除
    for (int i = array.count - 1; i >= 0;i--) {
        NSIndexPath * path = array[i];
        [_dataArray removeObjectAtIndex:path.row];
        NSLog(@"%d",path.row);
    }
    //重新加载数据
    [_tableView reloadData];
    //删除并且 有动画
    //[_tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
}</span>

 //使得tableView的编辑状态在相互切换
- (void)editTableView{
    _tableView.editing = !_tableView.editing;
}


#pragma mark --UIScrollViewDelegate--
//实现scrollView的代理方法

//下面这个方法 是只要scrollView在动 始终会调用这个方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //因为UITableView 是UIScrollView 的子类 所有判断我们是在点击哪个scrollView
    if (scrollView == _tableView) {
        //tableView的偏移量只是在y上面 所以当偏移量大于151时 让我们的导航栏慢慢消失
        if (scrollView.contentOffset.y > 151) {
            [UIView animateWithDuration:1 animations:^{
                self.navigationController.navigationBar.alpha = 0;
            }];
        }
        //当偏移量小于86时 让我们的导航栏再慢慢显示出来
        else if (scrollView.contentOffset.y < 86) {
            [UIView animateWithDuration:2 animations:^{
                //self.navigationController.navigationBarHidden = NO;
                self.navigationController.navigationBar.alpha = 1;
            }];
        }
    }
}


//这个是scrollView的代理方法中  最后一个执行的函数 停止减速的意思  在这里我们设置页面控制器和scrollView关联 当scrollView达到一定的偏移量 就是另一个页面 控制器也随之变化
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
   <span style="background-color: rgb(204, 204, 204);"> //当我们点击的是tableView时 不做操作
    if (scrollView == _tableView) {
        
    }
    //当时scrollView时 我们通过计算改变pageControl的page值
    else{
        NSInteger page = scrollView.contentOffset.x / 320;
        _pageControl.currentPage = page;
    }</span>
}


#pragma mark --UITableViewDeleagate
//此方法必须实现 返回的是一个分组内有多少行 因为我们就一个组 所以直接返回数据源数组的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //返回数据源元素的个数
    //如果是tableView  就返回数据源_dataArray的元素个数
    if (tableView == _tableView) {
        return _dataArray.count;
    }
   <span style="background-color: rgb(204, 204, 204);"> //如果是搜索的那个视图
    else{
        
        //如果数组不存在 就创建一个新的数组
        if (_searchResultDataArray == nil) {
            _searchResultDataArray = [[NSMutableArray alloc] init];
        }
        //如果存在 就清空数组
        else{
            [_searchResultDataArray removeAllObjects];
        }
        //得到搜索栏中得字符串_searchBar.text 然后再数据源_dataArray中的元素查找
        //然后找到与搜索栏中有关系的元素添加大搜索栏的数据数组中
        for (NSString * string in _dataArray) {
            NSRange range = [string rangeOfString:_searchBar.text];
            if (range.location != NSNotFound) {
                [_searchResultDataArray addObject:string];
            }
        }
        //返回搜索栏中数组的个数
        return _searchResultDataArray.count;
    }</span>
    
}
//此方法和上面这个方法一样 必须得实现 返回的是cell  重复使用cell的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //首先 tableView会找带有标记@"snail"的闲置的cell
    UITableViewCell * tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"snail"];
    //如果没有的话 就自动创建 并且把标记@"snail"写上
    if (!tableViewCell) {
        tableViewCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"snail"];
    }
    if (tableView == _tableView) {
        // indexPath 有两部分组成 一个是:某行indexPath.row 另一个是:某组indexPath.section
        //cell上面的textLabel上面加上我们数组对应的字符串  _dataArray
        tableViewCell.textLabel.text = _dataArray[indexPath.row];
        //这里给cell的详情标签上再添加文字
        tableViewCell.detailTextLabel.text = _dataArray[indexPath.row];
    }<span style="background-color: rgb(204, 204, 204);">else{
        //删除的cell上面的textLabel上面加上我们删除数组对应的字符串  _searchResultDataArray
        tableViewCell.textLabel.text = _searchResultDataArray[indexPath.row];
        //这里给cell的详情标签上再添加文字
        tableViewCell.detailTextLabel.text = _searchResultDataArray[indexPath.row];
    }</span>
    
    
    
    //给cell添加一个图片
    [tableViewCell.imageView setImage:[UIImage imageNamed:@"star_icon@2x.png"]];

    return tableViewCell;
}

//返回的是tableViewCell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

//选中每个tableViewCell调用的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击cell后 不点击后使得cell处于未点击状态 并且有动画
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    <span style="background-color: rgb(204, 204, 204);">//如果tableView正在在编辑 什么操作也不作
    if (tableView.editing == YES) {
        
    }else{
        //不是打开的 才可以点击行的操作
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    </span>
}


#warning 关于操作cell的代理方法
//此方法是设置每个tableView是否可以被编辑 YES可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
<span style="background-color: rgb(204, 204, 204);">//设置每个cell 如果被编辑 将会执行什么编辑
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    //返回cell的多选样式
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    
    
    
    /* 删除一个
    //当行数是偶数时  我们设此cell 如果执行操作 就是删除的操作
    if (indexPath.row % 2 == 0) {
        return UITableViewCellEditingStyleDelete;
    }else{
        //奇数时  插入的操作
        return UITableViewCellEditingStyleInsert ;
    }
     */
}</span>
//此方法 是根据上面为每个cell设置的操作形式 来进行真正的操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //如果cell是删除的形式 那我们就删除此cell
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //首先 把数据源里面的数据移除
        [_dataArray removeObjectAtIndex:indexPath.row];
        //然后tableView在删除某行  动画可以很多种
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
         }else if (editingStyle == UITableViewCellEditingStyleInsert){
             //如果是插入操作
             //记录下插入的位置
             NSInteger row = indexPath.row;
             //插入cell后将要再cell上显示的信息
             NSString * insertStr = @"添加行";
             //首先在数据源添加此数据
             [_dataArray insertObject:insertStr atIndex:row];
             //再在tableView上插入一行
             [tableView insertRowsAtIndexPaths:@[indexPath]
                              withRowAnimation:UITableViewRowAnimationRight];
         }
}

//设置每个cell往左移动时 显示的字符串
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#warning 关于cell移动的代理方法
//设置cell是否可以被移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//对cell进行移动 sourceIndexPath源cell位置   destinationIndexPath目的位置
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    
    //记录下哪行cell要移动
    NSInteger fromRow = sourceIndexPath.row;
    //记录下cell将要被移动到哪行
    NSInteger toRow = destinationIndexPath.row;
    //把要移动那行的数据拿出来
    id obj = _dataArray[fromRow];
    //把要移动的那行对应在array中得数据删除
    [_dataArray removeObject:obj];
    //然后再移动的目标位置对应的array数据源添加上数据
    [_dataArray insertObject:obj atIndex:toRow];
    //然后让tableView重新载入数据
    [tableView reloadData];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值