我在這裏第一次使用手勢進行操作。請讓我知道,如果我的方法是錯誤的或任何更好的解決方案。在水龍頭手勢上重置CollectionviewviewCell的位置
我想刪除左邊的collectionView Cell,就像UITableview刪除函數一樣。刪除工作正常。現在,我要的是,有一次,我刷的單元格,點擊屏幕任意上的CollectionView應該刷回原來的位置(同樣喜歡的tableview刪除行功能)
我使用/嘗試這種代碼 更新viewDidLoad中和竊聽事件
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
self.view.addGestureRecognizer(tap)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CustomCell
Cell.backgroundColor = UIColor.white
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(delete(sender:)))
leftSwipe.direction = UISwipeGestureRecognizerDirection.left
Cell.addGestureRecognizer(leftSwipe)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
Cell.addGestureRecognizer(tap)
Cell.deleteButton.addTarget(self, action: #selector(DeleteCell(sender:)), for: .touchUpInside)
}
func tapped(_ recognizer: UITapGestureRecognizer) {
// self.collectionView.performBatchUpdates({
//self.collectionView.reloadSections(NSIndexSet(index: 0) as IndexSet)
//}, completion: nil)
let point = recognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: point)
let cell = self.collectionView.cellForItem(at: indexPath!)
UIView.animate(withDuration: 0.4) {
cell?.contentView.frame = CGRect(x: 0, y: 0, width: (cell?.contentView.frame.width)!, height: (cell?.contentView.frame.height)!)
}
}
func delete(sender: UISwipeGestureRecognizer){
let cell = sender.view as! CustomCell
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: -90, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
}
func DeleteCell(sender : AnyObject){
let cell = sender.superview as! CustomCell
let i = self.collectionView.indexPath(for: cell)!.item
let indexpath = self.collectionView.indexPath(for: cell)
let array : NSMutableArray = []
self.collectionView.performBatchUpdates({
self.userArray.remove(at: i)
array.add(indexpath!)
self.collectionView.deleteItems(at:array as! [IndexPath])
}, completion: nil)
}
class CustomCell: UICollectionViewCell {
let deleteButton: UIButton = {
let deleteBtn = UIButton()
deleteBtn.setImage(UIImage(named: "red"), for: .normal)
deleteBtn.contentMode = .scaleAspectFit
return deleteBtn
}()
}
所以我在這裏能夠通過self.collectionView.performBatchUpdates,但它不是平滑的動畫設置單元格的位置回到原來的。我嘗試使用
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: 0, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
但它只適用於如果刷卡的細胞攻絲,而不是任何其他細胞或其他地方。任何的意見都將會有幫助!!
謝謝jacolack!我試過了,它是一樣的。只有當我點擊選中的單元格時,單元格纔會返回。 – iUser
你將這個添加到哪個類? – Jacolack
嘿,對不起,但沒有得到你在這裏問的課程。我上面更新了我的代碼。請看看它。 – iUser