本文译自:Cookbook: Moving Table View Cells with a Long Press Gesture

目录:

  • 你需要什么?
  • 如何做?
  • 如何将其利用至UICollectionView上?
  • 何去何从?

本次的 cookbook-style 教程中介绍如何通过长按手势来移动 table view中的cell,这种操作方式就像苹果自家的天气 App 一样。

你可以直接把本文中的到吗添加到你的工程中,或者将其添加到我为你创建好的 starter project 中,也可以下载本文的完整示例工程

你需要什么?

  • UILongGestureRecognizer
  • UITableView (可以用 UICollectionView 替代之)
  • UITableViewController (可以用 UIViewController 或 UICollectionViewController 替代之)
  • 5 分钟。

如何做?

首先给 table view 添加一个 UILongGestureRecognizer。可以在 table view controller 的 viewDidLoad 方法中添加。

1
2
3
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(longPressGestureRecognized:)];
[self.tableView addGestureRecognizer:longPress];

记者为 gesture recognizer 添加 action 方法。该方法首先应该获取到在 table view 中长按的位置,然后找出这个位置对应的 cell 的 index。记住:这里获取到的 index path 有可能为 nil(例如,如果用户长按在 table view的section header上)。

1
2
3
4
5
6
7
8
9
10
- (IBAction)longPressGestureRecognized:(id)sender {
 
UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
UIGestureRecognizerState state = longPress.state;
 
CGPoint location = [longPress locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
 
// More coming soon...
}

接着你需要处理UIGestureRecognizerStateBegan分支。如果获取到一个有效的 index path(non-nil),就去获取对应的 UITableViewCell,并利用一个 helper 方法获取这个 table view cell 的 snapshot view。然后将这个 snapshot view 添加到 table view 中,并将其 center 到对应的 cell上。

为了更好的用户体验,以及更自然的效果,在这里我把原始 cell 的背景设置为黑色,并给 snapshot view 增加淡入效果,让 snapshot view 比 原始 cell 稍微大一点,将它的Y坐标偏移量与手势的位置的Y轴对齐。这样处理之后,cell 就像从 table view 中跳出,然后浮在上面,并捕捉到用户的手指。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
static UIView *snapshot = nil; ///< A snapshot of the row user is moving.
static NSIndexPath *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
 
switch (state) {
case UIGestureRecognizerStateBegan: {
if (indexPath) {
sourceIndexPath = indexPath;
 
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
 
// Take a snapshot of the selected row using helper method.
snapshot = [self customSnapshotFromView:cell];
 
// Add the snapshot as subview, centered at cell's center...
__block CGPoint center = cell.center;
snapshot.center = center;
snapshot.alpha = 0.0;
[self.tableView addSubview:snapshot];
[UIView animateWithDuration:0.25 animations:^{
 
// Offset for gesture location.
center.y = location.y;
snapshot.center = center;
snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
snapshot.alpha = 0.98;
 
// Black out.
cell.backgroundColor = [UIColor blackColor];
} completion:nil];
}
break;
}
// More coming soon...
}

将下面的方法添加到 .m 文件的尾部。该方法会根据传入的 view,返回一个对应的 snapshot view。

1
2
3
4
5
6
7
8
9
10
11
- (UIView *)customSnapshotFromView:(UIView *)inputView {
 
UIView *snapshot = [inputView snapshotViewAfterScreenUpdates:YES];
snapshot.layer.masksToBounds = NO;
snapshot.layer.cornerRadius = 0.0;
snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
snapshot.layer.shadowRadius = 5.0;
snapshot.layer.shadowOpacity = 0.4;
 
return snapshot;
}

当手势移动的时候,也就是UIGestureRecognizerStateChanged分支,此时需要移动 snapshot view(只需要设置它的 Y 轴偏移量即可)。如果手势移动的距离对应到另外一个 index path,就需要告诉 table view,让其移动 rows。同时,你需要对 data source 进行更新:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
case UIGestureRecognizerStateChanged: {
CGPoint center = snapshot.center;
center.y = location.y;
snapshot.center = center;
 
// Is destination valid and is it different from source?
if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
 
// ... update data source.
[self.objects exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
 
// ... move the rows.
[self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
 
// ... and update source so it is in sync with UI changes.
sourceIndexPath = indexPath;
}
break;
}
// More coming soon...

最后,当手势结束或者取消时,table view 和 data source 都是最新的。你所需要做的事情就是将 snapshot view 从 table view 中移除,并把 cell 的背景色还原为白色。

为了提升用户体验,我们将 snapshot view 淡出,并让其尺寸变小至与 cell 一样。这样看起来就像把 cell 放回原处一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
default: {
// Clean up.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];
[UIView animateWithDuration:0.25 animations:^{
 
snapshot.center = cell.center;
snapshot.transform = CGAffineTransformIdentity;
snapshot.alpha = 0.0;
 
// Undo the black-out effect we did.
cell.backgroundColor = [UIColor whiteColor];
 
} completion:^(BOOL finished) {
 
[snapshot removeFromSuperview];
snapshot = nil;
 
}];
sourceIndexPath = nil;
break;
}

就这样,搞定了!编译并运行程序,现在可以通过长按手势对 tableview cells重新排序!

你可以在 GitHub 上下载到完整的示例工程

如何将其利用至UICollectionView上?

假设你已经有一个示例工程使用了 UICollectionView,那么你可以很简单的就使用上本文之前介绍的代码。所需要做的事情就是用 self.collectionView替换掉 self.tableView,并更新一下获取和移动 UICollectionViewCell 的调用方法。

这里有个练习,从 GitHub上 checkout 出 UICollectionView 的starter project,然后将 tap-和-hold 手势添加进去以对 cells 进行重排。这里可以下载到已经实现好了工程

iOS 利用长按手势移动 Table View Cells的更多相关文章

  1. Table View Programming Guide for iOS---(六)---A Closer Look at Table View Cells

    A Closer Look at Table View Cells A table view uses cell objects to draw its visible rows and then c ...

  2. Table View Programming Guide for iOS---(一)---About Table Views in iOS Apps

    About Table Views in iOS Apps Table views are versatile user interface objects frequently found in i ...

  3. 创建一个Table View

    在本课程中,您将创建应用程序FoodTracker的主屏幕.您将创建第二个,表视图为主场景,列出了用户的菜谱.你会设计定制表格单元格显示每一个菜谱,它是这样的: 学习目标 在课程结束时,你将能够: 创 ...

  4. How To Make A Swipeable Table View Cell With Actions – Without Going Nuts With Scroll Views

    How To Make A Swipeable Table View Cell With Actions – Without Going Nuts With Scroll Views  Ellen S ...

  5. Table View Programming Guide for iOS---(七)---Managing Selections

    Managing Selections 管理选择 When users tap a row of a table view, usually something happens as a result ...

  6. Table View Programming Guide for iOS---(五)---Creating and Configuring a Table View

    Creating and Configuring a Table View Your app must present a table view to users before it can mana ...

  7. Table View Programming Guide for iOS---(三)----Overview of the Table View API

    Overview of the Table View API 表格视图API概述 The table view programming interface includes several UIKit ...

  8. Table View Programming Guide for iOS---(二)----Table View Styles and Accessory Views

    Table View Styles and Accessory Views 表格视图的风格以及辅助视图 Table views come in distinctive styles that are ...

  9. iOS学习之Table View的简单使用

    Table View简单描述: 在iPhone和其他iOS的很多程序中都会看到Table View的出现,除了一般的表格资料展示之外,设置的属性资料往往也用到Table View,Table View ...

随机推荐

  1. 网络爬虫urllib2 tornado

    百度不支持用tornado请求,可以用美团开放API 测试. import tornado.httpclient def fetch(url): http_header={'User-Agent':' ...

  2. js中的包装对象。

    我们都知道在js中普通类型的变量是没有属性和方法的,然后有时却并不是这样. var str = "努力,奋斗"; console.log(str.length); var num ...

  3. linux2.6.24内核源代码分析(2)——扒一扒网络数据包在链路层的流向路径之一

    在2.6.24内核中链路层接收网络数据包出现了两种方法,第一种是传统方法,利用中断来接收网络数据包,适用于低速设备:第二种是New Api(简称NAPI)方法,利用了中断+轮询的方法来接收网络数据包, ...

  4. 比较HTML元素和Native组件的区别

    我们开发web应用,会使用到各种Html基本元素,比较<div>,<span>,<img>等. 当我们在开发React Native时,我们不能使用HTML元素,但 ...

  5. Unity3D 角色(物体) 移动方法 合集

    1. 简介 在Unity3D中,有多种方式可以改变物体的坐标,实现移动的目的,其本质是每帧修改物体的position. 2. 通过Transform组件移动物体 Transform 组件用于描述物体在 ...

  6. Bucky – 免费开源的实时用户监控工具

    Bucky 是一个开源的实时用户监控工具,用于衡量用户在浏览器中使用 Web 应用程序时的性能.它可以自动测量你的网页需要多长时间来加载,Ajax 请求需要多长时间和各个函数需要实行多久. 您可能感兴 ...

  7. css中zoom和transform:scale的区别

    css中zoom和transform:scale的区别 关于zoom: 以前只是看到别人的代码中用过zoom,自己从未使用过,今天在探究ie7兼容inline-block时,发现里面提到了zoom.下 ...

  8. java和javascript双引号嵌套的问题

    双引号不能嵌套双引号,否则一对双引号就结束了. java中双引号中嵌套双引号需要转义: /** * java双引号转义符测试 * @author asus * */ public static voi ...

  9. JavaScript--DOM修改元素的属性

    一旦你获得了要修改的元素,可以有2种方式,来读取和修改它的属性:一种老的方式(它被更多的用户代理所支持)和一种新的DOM方法的方式.老的和新的用户代理都允许你以对象属性的方式获取和设置元素的属性. 先 ...

  10. DotNetCore跨平台~Startup类的介绍

    新宠儿 DotNetCore是.net5.0版本,之所以不叫.net5.0为的就是不让我们把它与前面的.net混为一淡,它将是真正意义的跨平台开发语言,在网上也有相关介绍,中国的一些大牛也发了相关文章 ...