【发布时间】:2016-12-12 17:12:02
【问题描述】:
我正在尝试复制 iOS 的滑动删除功能。我知道它可以立即在 tableview 上使用,但是我需要构建的 UI 从 Collection View 中受益。因此,我需要一个自定义实现,我将使用向上滑动手势。幸运的是,这是我自己设法实现的,但是我很难弄清楚我需要如何设置滑动删除/点击删除/忽略功能。
所以我正在使用以下集合视图:
func buildCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 4;
collectionView = UICollectionView(frame: CGRect(x: 0, y: screenSize.midY - 120, width: screenSize.width, height: 180), collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(VideoCell.self, forCellWithReuseIdentifier: "videoCell")
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.contentInset = UIEdgeInsetsMake(0, 20, 0, 30)
collectionView.backgroundColor = UIColor.white()
collectionView.alpha = 0.0
//can swipe cells outside collectionview region
collectionView.layer.masksToBounds = false
swipeUpRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.deleteCell))
swipeUpRecognizer.delegate = self
collectionView.addGestureRecognizer(swipeUpRecognizer)
collectionView.isUserInteractionEnabled = true
}
我的自定义视频单元包含一个图像,其下方是删除按钮。因此,如果您向上滑动图像,则会弹出删除按钮。不确定这是否是正确的方法:
class VideoCell : UICollectionViewCell {
var deleteView: UIButton!
var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
deleteView = UIButton(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
deleteView.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(deleteView)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
imageView.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我正在使用以下逻辑:
func deleteCell(sender: UIPanGestureRecognizer) {
let tapLocation = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: tapLocation)
if velocity.y < 0 {
//detect if there is a swipe up and detect it's distance. If the distance is far enough we snap the cells Imageview to the top otherwise we drop it back down. This works fine already.
}
}
但问题从这里开始。一旦我的单元格超出 collectionview 边界,我就无法再访问它了。我仍然想进一步滑动它以将其删除。我只能通过滑动删除按钮来做到这一点,但我希望它上面的 Imageview 也可以滑动。或者,如果我点击 collectionview 之外的图像,它应该滑回该行而不是删除它。
如果我增加 collectionview 边界,我可以防止这个问题,但我也可以滑动以移除单元格的可见高度之外。这是由 collectionview 中的 tapLocation 引起的,它检测到 indexPath。我不想要的东西。我希望向上滑动只适用于 collectionview 的单元格。
按钮和图像也会相互干扰,因为我无法区分它们。它们都在同一个单元格中,这就是为什么我想知道是否应该在单元格中设置删除按钮。或者我应该把它放在哪里?我还可以用它制作两个按钮并根据状态禁用用户交互,但不确定最终会如何。
【问题讨论】:
标签: ios swift uipangesturerecognizer collectionview