UITableViewCell的移动

看到Metro大都会 这个App中扣款顺序有个cell可以移动,于是觉得是时候回忆一下UITableView的基本使用了。其实他这个移动cell的功能是系统自带的。

 

代码主要是这样:

//
//  ViewController.m
//  UITableViewCell移动Demo
//
//  Created by LiuWei on 2018/3/12.
//  Copyright © 2018年 xxx. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //允许编辑
    [_tableView setEditing:YES];
}

#pragma Mark -- UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"我是第%lu个cell",indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//默认编辑模式下,每个cell左边有个红色的删除按钮,设置为None即可去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}
//是否允许indexPath的cell移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//实现该方法 cell右侧出现3条横线
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //NSIndexPath 有section和row属性可调用 能找到数据源
    NSLog(@"s = %@ -- d = %@",sourceIndexPath,destinationIndexPath);
    
}

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


@end

 

如果要自定义移动效果,参考他的做法:https://www.jianshu.com/p/ce382f9bc794 

 

posted @ 2018-03-12 13:18  liuw_flexi  阅读(294)  评论(0编辑  收藏  举报