如何为 UICollectionView 实现 UITableView 的滑动删除 [英] How to implement UITableView`s swipe to delete for UICollectionView

查看:84
本文介绍了如何为 UICollectionView 实现 UITableView 的滑动删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问如何在 UICollectionView 中实现与 UITableView 的滑动删除相同的行为.我正在寻找教程,但找不到任何教程.

I just like to ask how can I implement the same behavior of UITableView`s swipe to delete in UICollectionView. I am trying to find a tutorial but I cannot find any.

另外,我正在使用 PSTCollectionView 包装器来支持 iOS 5.

Also, I am using PSTCollectionView wrapper to support iOS 5.

谢谢!

滑动识别器已经很好了.我现在需要的是取消删除模式时与 UITableView 相同的功能,例如当用户点击表格视图中的单元格或空白区域时(即,当用户在删除"按钮之外点击时).UITapGestureRecognizer 不起作用,因为它只检测释放触摸时的点击.UITableView 在手势开始时检测到触摸(而不是在释放时),并立即取消删除模式.

The swipe recognizer is already good. What I need now is the same functionality as UITableView's when cancelling the Delete mode, e.g. when user taps on a cell or on a blank space in the table view (that is, when user taps outside of the Delete button). UITapGestureRecognizer won't work, since it only detects taps on release of a touch. UITableView detects a touch on begin of the gesture (and not on release), and immediately cancels the Delete mode.

推荐答案

有一个更简单的解决方案可以避免使用手势识别器.该解决方案基于 UIScrollView 结合 UIStackView.

There is a simpler solution to your problem that avoids using gesture recognizers. The solution is based on UIScrollView in combination with UIStackView.

  1. 首先,您需要创建 2 个容器视图 - 一个用于单元格的可见部分,一个用于隐藏部分.您将这些视图添加到 UIStackView.stackView 将充当内容视图.确保视图的宽度与 stackView.distribution = .fillEqually 相同.

  1. First, you need to create 2 container views - one for the visible part of the cell and one for the hidden part. You’ll add these views to a UIStackView. The stackView will act as a content view. Make sure that the views have equal widths with stackView.distribution = .fillEqually.

您将把 stackView 嵌入到启用了分页的 UIScrollView 中.scrollView 应该被限制在单元格的边缘.然后将 stackView 的宽度设置为 scrollView 的宽度的 2 倍,这样每个容器视图都将具有单元格的宽度.

You’ll embed the stackView inside a UIScrollView that has paging enabled. The scrollView should be constrained to the edges of the cell. Then you’ll set the stackView’s width to be 2 times the scrollView’s width so each of the container views will have the width of the cell.

通过这个简单的实现,您已经创建了具有可见和隐藏视图的基本单元.使用可见视图向单元格添加内容,在隐藏视图中您可以添加删除按钮.这样你就可以实现:

With this simple implementation, you have created the base cell with a visible and hidden view. Use the visible view to add content to the cell and in the hidden view you can add a delete button. This way you can achieve this:

我在 GitHub 上建立了一个 示例项目.您还可以在此处阅读有关此解决方案的更多信息.
此解决方案的最大优点是简单,您不必处理约束和手势识别器.

I've set up an example project on GitHub. You can also read more about this solution here.
The biggest advantage of this solution is the simplicity and that you don't have to deal with constraints and gesture recognizers.

这篇关于如何为 UICollectionView 实现 UITableView 的滑动删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆