我有一个UICollectionView,其中包含从我的AssignmentManager类填充的单元格。当用户想要删除作业时,他们按住一个单元格以便删除按钮以显示在他们单击的单元格上。使用下面的代码,当用户单击一个单元格时,每个单元格上都会显示删除按钮。如何使用UIGestureRecognizer解决此问题?如何指定用户在我的代码中按下并保留的单个单元格?任何帮助将不胜感激。
*有些注意事项:我只包含了我认为与问题相关的代码。如果需要,我可以添加更多。也是的,我把missButton拼错为delteButton。如果这让任何人感到困惑,我很抱歉。
var userWantsToRemoveDeleteButton: Bool = false
var userDelete: Bool = false
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! homeworkcell
cell.delteButton.hidden = true
cell.delteButton.enabled = false
if userDelete == true {
cell.delteButton.hidden = false
cell.delteButton.enabled = true
if userWantsToRemoveDeleteButton == true {
cell.delteButton.hidden = true
cell.delteButton.enabled = false
}
}
// add button gestures
cell.delteButton?.layer.setValue(indexPath.item, forKey: "index")
cell.delteButton?.addTarget(self, action: "deleteAssignment:", forControlEvents: UIControlEvents.TouchUpInside)
// add the swipe gestures
let longPress = UILongPressGestureRecognizer(target: self, action: "deleteMode:")
cell.addGestureRecognizer(longPress)
let assignments = AssignmentManager.assignments[indexPath.item]
cell.myLabel.text = assignments.title
cell.assignment = assignments
cell.dueLabel.text = dateString
cell.myLabel.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor.blueColor()
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
func deleteMode(sender: UISwipeGestureRecognizer) {
userDelete = true
userWantsToRemoveDeleteButton = false
collectionView.reloadData()
doneEditingButton.enabled = true
}
func deleteAssignment(sender: UIButton) {
let i : Int = (sender.layer.valueForKey("index")) as! Int
AssignmentManager.deleteAssignment(i)
NSUserDefaultsManager.synchronize()
collectionView.reloadData()
}
答案 0 :(得分:0)
嗯,这种情况正在发生,因为userDelete变为true,然后按钮显示在每个单元格中。您应该记住按下哪个单元格用户。所以也许可以在单元格中添加标签(indexPath.row),然后在deleteMode函数中调用reload方法。然后在cellForRow方法中检查selectedTag
是否等于indexPath.row并显示按钮(如果是),否则隐藏它。
这只是一个快速的例子,你可以做到这一点......