Swift CollectionView 使用滑动手势删除项目
Posted
技术标签:
【中文标题】Swift CollectionView 使用滑动手势删除项目【英文标题】:Swift CollectionView Remove Items with swipe gesture 【发布时间】:2015-04-27 07:10:35 【问题描述】:我有一个水平滚动的集合视图。
我正在寻找通过向上或向下滑动手势来移除项目的简洁方法。 重新排列元素也会很棒,但目前移除更为重要。
我找到了一些 Obj-C 文档,但是,由于我还是 swift Obj-C 的新手,所以对我来说太多了。
【问题讨论】:
那么到目前为止,您离我们有多近?即使更改未保存,您是否可以抓取物品并四处移动? This very related question 有针对 Objective-C 的答案,但是您应该能够轻松地为那里列出的少数 API 找到 Swift 等价物... 【参考方案1】:过去几天我一直在处理同样的情况。 这是我对 swift 所做的。我检查了 Michael 的链接并进行了一些研究...
所以..
添加这个
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.
【讨论】:
非常感谢..我实际上做了类似的事情,但你的解决方案更整洁 你也可以继承手势识别器并传递 indexPath【参考方案2】:您也可以通过在单元格中使用多个视图来实现。 这是我的代码。首先使用三个视图。
示例:-
@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 )
现在手势识别器将在该特定视图上工作,看起来就像您正在滑动集合视图单元格。
【讨论】:
以上是关于Swift CollectionView 使用滑动手势删除项目的主要内容,如果未能解决你的问题,请参考以下文章
iOS - 在视图(Swift)中为多个Tableview或Collectionviews使用/传递手势识别器
iOS - 使用/传递手势识别器用于视图中的多个表视图或集合视图(Swift)