iOS点击按钮移动cell

前些天遇到这样一个需求,点击cell的按钮 需要上下移动该cell.在这里记录一下 方便以后查阅.

效果是这样的:

下面列出完成这个需求的过程 所注意的点:

1.实现点击顶部按钮、底部按钮的action

W_S
    cell.upTapBlock = ^(UIButton *sender) {
        if (indexPath.row == 0) {
            return ;
        }
        //sourceIndexPath是被点击cell的IndexPath
        NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
        NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0];

        [self.discussMutableMsgs exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
        //移动cell的位置
        [weakSelf.previewTable moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
        
        [weakSelf.previewTable reloadRowsAtIndexPaths:@[sourceIndexPath,destinationIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    };

    
    cell.downTapBlock = ^(UIButton *sender) {
        if (indexPath.row == self.discussMutableMsgs.count - 1) {
            return ;
        }
        
        //sourceIndexPath是被点击cell的IndexPath
        NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
        NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];

        [self.discussMutableMsgs exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
        //移动cell的位置
        [weakSelf.previewTable moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
        
        [weakSelf.previewTable reloadRowsAtIndexPaths:@[sourceIndexPath,destinationIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    };

2.注意通知系统哪些行可以移动
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
还需要注意的是 cell 复用会造成bug,于是在给cell 绑定数据的时候 
[self.contentView removeAllSubviews];

你可能感兴趣的:(iOS点击按钮移动cell)