我有一个水平滚动的集合视图。
我正在寻找一种简洁的方法来使用向上或向下滑动手势删除项目。
同时重新排列元素也会很棒,但目前删除更为重要。
我找到了一些Obj-C文档,但由于我对Swift Obj-C还不熟悉,这对我来说太难了。
所以...
添加这个
let cSelector = Selector("reset:")
let UpSwipe = UISwipeGestureRecognizer(target: self, action: cSelector )
UpSwipe.direction = UISwipeGestureRecognizerDirection.Up
cell.addGestureRecognizer(UpSwipe)
要实现这个功能,你需要在你的collectionView delegate方法中,添加下面的代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
接着,你需要定义一个选择器(selector),用来从你的数组中删除滑动的项目,然后重新加载你的collection view。
func reset(sender: UISwipeGestureRecognizer) {
let cell = sender.view as! UICollectionViewCell
let i = self.favoritesCV.indexPathForCell(cell)!.item
favoritesInstance.favoritesArray.removeAtIndex(i) //replace favoritesInstance.favoritesArray with your own array
self.favoritesCV.reloadData() // replace favoritesCV with your own collection view.
}
你也可以通过在单元格中使用多个视图来实现它。
这是我的代码。首先使用三个视图。
示例:
@IBOutlet weak var YOURVIEW: UIView!
@IBOutlet weak var edit: UIView!
@IBOutlet weak var delete: UIView!
现在对YOURVIEW的前导和尾随进行布局
@IBOutlet weak var YOURLEADING: NSLayoutConstraint!
@IBOutlet weak var YOURTRAILING: NSLayoutConstraint!
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeLeft.direction = .left
self.YOURTOPVIEW.addGestureRecognizer(swipeLeft
)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeRight.direction = .right
self.YOURTOPVIEW.addGestureRecognizer(swipeRight)
现在在类体中编写这段代码
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case .left:
self.animate()
self.YOURLEADING.constant = -100
self.YOURTRAILING.constant = 100
// YOUR OTHER ACTIONS HERE
case .right:
self.animate()
self.YOURLEADING.constant = 100
self.YOURTRAILING.constant = -100
// YOUR OTHER ACTIONS HERE
default:
break
}
}
}
同时编写一个函数来展示动画效果
func animate()
{
UIView.animate(withDuration: 1,
delay: 0.0,
animations: { () -> Void in
self.YOURTOPVIEW.frame = CGRect(x: 0, y: 0, width: self.YOURTOPVIEW.frame.width, height: self.YOURTOPVIEW.frame.height)
}, completion: { (finished: Bool) -> Void in })
}