IOS UITableView拖动排序功能

  UITbableView作为列表展示信息,除了展示的功能,有时还会用到删除,排序等功能,下面就来讲解一下如何实现排序。

  排序是当表格进入编辑状态后,在单元格的右侧会出现一个按钮,点击按钮,就可以拖动单元格,移动位置,进行手动排序。

IOS UITableView拖动排序功能_第1张图片IOS UITableView拖动排序功能_第2张图片

 

使用系统自带拖动排序功能的步骤:

1、让tableView进入编辑状态,也就是设置它的editing为YES

2、返回编辑模式,也就是实现UITableViewDelegate中的tableview:editingStyleForRowAtIndexPath:方法,在里面返回UITableViewCellEditingStyleNone模式。如果不实现,默认返回的就是删除模式

3、实现tableView:moveRowAtIndexPath:toIndexPath方法,只要实现该方法,就能实现单元格的拖动排序,但只是实现了表面的排序,并没有修改真实地数据

4、在方法中完成数据模型的更新

代码:

 
   
//  ViewController.m
//  JRTableView删除
//
//  Created by jerehedu on 15/6/11.
//  Copyright (c) 2015年 jerehedu. All rights reserved.
//

#import "ViewController.h"
#import "Goods.h"

@interface ViewController ()

{
    UITableView *_tableView; //列表
    
    NSMutableArray *_goodsAry; //商品数组
    
    UIButton *_editBtn; //编辑按钮
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
    titleLabel.text = @"购物车";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor redColor];
    titleLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:titleLabel];
    
    //添加编辑按钮
    _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _editBtn.frame = CGRectMake(self.view.frame.size.width-60, 25, 50, 34);
    [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_editBtn setTitle:@"完成" forState:UIControlStateSelected];
    _editBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _editBtn.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5];
    [self.view addSubview:_editBtn];
    [_editBtn addTarget:self action:@selector(clickEditBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    //添加tableview
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    //取数据
    NSArray *ary = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ShoppingGoodsList" ofType:@"plist"]];
    
    //把数据存到模型对象中,然后把对象存到数组中
    _goodsAry = [NSMutableArray array];
    for (int i=0; i

 

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

  疑问咨询或技术交流,请加入官方QQ群:JRedu技术交流 (452379712)

 

作者: 杰瑞教育
出处: http://blog.csdn.net/jerehedu/ 
本文版权归烟台杰瑞教育科技有限公司和CSDN共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 

你可能感兴趣的:(IOS技术分享)