IOS表格的移动和删除

简介
ios表格有UICollectionView、UITableView两种格式,下面简单的整理了一下这两种表格的移动和删除方法,有说得不对的请指正。
一、UICollectionView表格
不多说,直接上代码

UIViewController里实现
@property (nonatomic, retain) UIImageView *delectImg;//回收站
/**之前选中cell的NSIndexPath*/
@property (nonatomic, strong) NSIndexPath *oldIndexPath;
/**单元格的截图*/
@property (nonatomic, strong) UIView *snapshotView;
/**之前选中cell的NSIndexPath*/
@property (nonatomic, strong) NSIndexPath *moveIndexPath;
/*数据源*/
@property(nonatomic,retain)NSMutableArray *title_Arr;

//创建UICollectionView
self.title_Arr = [NSMutableArray arrayWithObjects:@"少",@"壮",@"不",@"努",@"力",@"老",@"大",@"徒",@"伤",@"悲", nil];
self.title=@"UICollectionView";
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-50) collectionViewLayout:flowLayout];
self.collectionView.backgroundColor=[UIColor blueColor];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerClass:[MoveCollectionViewCell class] forCellWithReuseIdentifier:@"uicollectionviewcell"];
[self.view addSubview:self.collectionView = self.collectionView];
//回收站
self.delectImg=[[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-110, SCREEN_HEIGHT-210, 80, 80)];
UIImage *i = [UIImage imageNamed:@"btn_delete-application_sel.png"];
self.delectImg.image=i;
// 添加长按手势
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
[self.collectionView addGestureRecognizer:longPress];

pragma mark - UICollectionViewDataSource实现代理

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.title_Arr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MoveCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"uicollectionviewcell" forIndexPath:indexPath];
    cell.nameLab.text  = self.title_Arr[indexPath.row];;
    return cell;
}
//定义每个section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//定义每个UICollectionView 的大小(返回CGSize:宽度和高度)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(63, 103);
}
//定义每个UICollectionView 的间距(返回UIEdgeInsets:上、左、下、右)
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(20, (SCREEN_WIDTH-252)/5, 10, (SCREEN_WIDTH-252)/5);
}
//两个cell之间的间距(同一行的cell的间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
//这个是两行cell之间的间距(上下行cell的间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 30;
}

pragma mark - 长按手势

- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
        [self action:longPress];
    } else {
        [self iOS9_Action:longPress];
    }
}
//iOS9之后的实现
#pragma mark - iOS9 之后的方法
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 返回YES允许row移动
    return YES;
}
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //取出移动row数据
    id alldata = self.title_Arr[sourceIndexPath.row];
    //从数据源中移除该数据
    [self.title_Arr removeObject:alldata];
    //将数据插入到数据源中的目标位置
    [self.title_Arr insertObject:alldata atIndex:destinationIndexPath.row];
}
- (void)iOS9_Action:(UILongPressGestureRecognizer *)longPress
{
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:{ //手势开始
            //判断手势落点位置是否在row上
            [self.view addSubview:self.delectImg];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"indexPath"];
            [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"indexPath"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            if (indexPath == nil) {
                break;
            }
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            [self.view bringSubviewToFront:cell];
            //iOS9方法 移动cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
        { // 手势改变
            // iOS9方法 移动过程中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
            CGPoint endPoint = [longPress locationInView:self.view];
            CGFloat longS = sqrt(pow((endPoint.x-SCREEN_WIDTH+60), 2) + pow((endPoint.y-SCREEN_HEIGHT+180), 2));
            if (longS <= 160) {
                self.delectImg.frame = CGRectMake(SCREEN_WIDTH-120, SCREEN_HEIGHT-200, 100, 100);
            } 
        }
            break;
        case UIGestureRecognizerStateEnded:
        { // 手势结束
            // iOS9方法 移动结束后关闭cell移动 
            NSInteger indexPath= [[NSUserDefaults standardUserDefaults]integerForKey:@"indexPath"];
            NSIndexPath *indexPathStr = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            if (indexPathStr == nil) {
                CGPoint endPoint = [longPress locationInView:self.view];
                CGFloat longS = sqrt(pow((endPoint.x-SCREEN_WIDTH+60), 2) + pow((endPoint.y-SCREEN_HEIGHT+180), 2));
                if (longS <= 160) {
                    [self CancelAttention:indexPath];
                }
            }
            [self.collectionView endInteractiveMovement];
            [self.delectImg removeFromSuperview];
            self.delectImg.frame=CGRectMake(SCREEN_WIDTH-110, SCREEN_HEIGHT-210, 80, 80);
        }
            break;
        default: //手势其他状态
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}
//.iOS9之前的实现
#pragma mark - iOS9 之前的方法
- (void)action:(UILongPressGestureRecognizer *)longPress
{
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
        { // 手势开始
            //判断手势落点位置是否在row上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            self.oldIndexPath = indexPath;
            if (indexPath == nil) {
                break;
            }
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            // 使用系统的截图功能,得到cell的截图视图
            UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO];
            snapshotView.frame = cell.frame;
            [self.view addSubview:self.snapshotView = snapshotView];
            // 截图后隐藏当前cell
            cell.hidden = YES;
            CGPoint currentPoint = [longPress locationInView:self.collectionView];
            [UIView animateWithDuration:0.25 animations:^{
                snapshotView.transform = CGAffineTransformMakeScale(1.05, 1.05);
                snapshotView.center = currentPoint;
            }];
        }
            break;
        case UIGestureRecognizerStateChanged:
        { // 手势改变
            //当前手指位置 截图视图位置随着手指移动而移动
            CGPoint currentPoint = [longPress locationInView:self.collectionView];
            self.snapshotView.center = currentPoint;
            // 计算截图视图和哪个可见cell相交
            for (UICollectionViewCell *cell in self.collectionView.visibleCells) {
                // 当前隐藏的cell就不需要交换了,直接continue
                if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) {
                    continue;
                }
                // 计算中心距
                CGFloat space = sqrtf(pow(self.snapshotView.center.x - cell.center.x, 2) + powf(self.snapshotView.center.y - cell.center.y, 2));
                // 如果相交一半就移动
                if (space <= self.snapshotView.bounds.size.width / 2) {
                    self.moveIndexPath = [self.collectionView indexPathForCell:cell];
                    //移动 会调用willMoveToIndexPath方法更新数据源
                    [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath];
                    //设置移动后的起始indexPath
                    self.oldIndexPath = self.moveIndexPath;
                    break;
                }
            }
        }
            break;
        default:
        { // 手势结束和其他状态
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:self.oldIndexPath];
            // 结束动画过程中停止交互,防止出问题
            self.collectionView.userInteractionEnabled = NO;
            [self.delectImg removeFromSuperview];
            // 给截图视图一个动画移动到隐藏cell的新位置
            [UIView animateWithDuration:0.25 animations:^{
                self.snapshotView.center = cell.center;
                self.snapshotView.transform = CGAffineTransformMakeScale(1.0, 1.0);
            } completion:^(BOOL finished) {
                // 移除截图视图,显示隐藏的cell并开始交互
                [self.snapshotView removeFromSuperview];
                cell.hidden = NO;
                self.collectionView.userInteractionEnabled = YES;
            }];
        }
            break;
    }
}
//删除应用
-(void)CancelAttention:(NSInteger)index{
    [self.title_Arr removeObjectAtIndex:index];
    [self.collectionView reloadData];
}
MoveCollectionViewCell里实现
-(id)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        [self addSubview:self.nameLab];
    }
    return self;
}
-(UILabel *)nameLab{
    if (!_nameLab) {
        self.nameLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
        self.nameLab.textColor=[UIColor blackColor];
        self.nameLab.lineBreakMode=NSLineBreakByWordWrapping;
        self.nameLab.backgroundColor= [UIColor redColor];
        self.nameLab.numberOfLines = 0;
        self.nameLab.font=[UIFont systemFontOfSize:16];
        self.nameLab.textAlignment=NSTextAlignmentCenter;
    }
    return _nameLab;
}

二、UITableView表格

UIViewController里实现
@property (nonatomic, strong) UITableView *myTableView;
//创建UITableView
self.title=@"UITableView";
self.myTableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-50) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
self.myTableView.scrollEnabled = YES;
self.myTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
self.myTableView.showsVerticalScrollIndicator = NO;
[self.myTableView setEditing:YES animated:YES];
[self.view addSubview:self.myTableView];

pragma mark--- UITableViewDataSource,UITableViewDelegate代理实现

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.title_Arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"UITableViewCell";
    MoveTableViewCell *tableCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (tableCell == nil) {
        tableCell = [[MoveTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
//    tableCell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    [tableCell name:self.title_Arr[indexPath.row]];
    return tableCell;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//确认编辑类型
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//移动方法
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    // 更换数据的顺序
    [self.title_Arr exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}
//删除方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 1.删除数据
        [self.title_Arr removeObjectAtIndex:indexPath.row];
        // 2.更新UITableView UI界面
        // [tableView reloadData];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
MoveTableViewCell里实现
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //设置点击样式
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //添加子控件
        [self addSubViews];
    }
    return self;
}
#pragma mark---添加子控件
- (void)addSubViews{
    self.name_lab =[[UILabel alloc] initWithFrame:CGRectMake(50, 0, SCREEN_WIDTH-100, 60)];
    self.name_lab.adjustsFontSizeToFitWidth = YES;
    self.name_lab.font = [UIFont systemFontOfSize:16];
    self.name_lab.numberOfLines = 0;
    self.name_lab.textColor= [UIColor darkTextColor];
    self.name_lab.textAlignment = NSTextAlignmentLeft;
    [self addSubview:self.name_lab];
}
- (void)name:(NSString *)nameStr{
    self.name_lab.text = nameStr;
}

你可能感兴趣的:(IOS表格的移动和删除)