我有一个水平滚动集合视图。
我正在寻找通过向上或向下滑动手势删除项目的巧妙方法。
重新排列元素也会很棒,但目前删除更重要。
文档,但是,由于我仍然是 swift Obj-C 的新手,这对我来说太多了。
过去几天我一直在处理同样的情况。这是我对 swift 所做的。我检查了迈克尔的链接,也做了一些研究......
所以。。
添加这个
let cSelector = Selector("reset:")
let UpSwipe = UISwipeGestureRecognizer(target: self, action: cSelector )
UpSwipe.direction = UISwipeGestureRecognizerDirection.Up
cell.addGestureRecognizer(UpSwipe)
自
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
然后定义您的选择器,它实际上会从数组中删除滑动的项目,然后重新加载您的集合视图。
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!
将此添加到覆盖 func awakeFromNib() 中
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 })
}
现在,手势识别器将处理该特定视图,并且看起来像您正在滑动集合视图单元格。