How to add a delete button to Collection View Cell in Swift?

心已入冬 提交于 2019-11-29 10:22:29

问题


Right now I have a list of scrolling usernames using a Collection View of buttons. But I’d like to add overlapping delete buttons to each row. They'd need to be attached to the name buttons and scroll with them.

How can I add these buttons to my CollectionView? (Also I'd like to skip the delete button on the first row for obvious reasons)

Current Code:

  //Add the cells to collection
  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
    cell.usernameLabel.text = userNames [indexPath.row]
    return cell
  }

  //Upon Selecting an item
  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    if (indexPath.row == 0){
      self.performSegueWithIdentifier("newUserSegue", sender: self)
    }
    else {
      sendData(userNames[indexPath.row])
      self.dismissViewControllerAnimated(true, completion: nil)
    }

  }

回答1:


Got it working! Here's how:

  1. I added a button to the cell in the Storyboard.
  2. Connected an outlet to the UICollectionViewCell class.
  3. Edited view controller code to:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
      let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
    
      cell.usernameLabel.text = userNames [indexPath.row]
    
      cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
      cell.deleteButton?.addTarget(self, action: "deleteUser:", forControlEvents: UIControlEvents.TouchUpInside)
    
      // Remove the button from the first cell
      if (indexPath.row == 0){
        var close : UIButton = cell.viewWithTag(11) as! UIButton
        close.hidden = true
      }
    
      return cell
    }
    
    func deleteUser(sender:UIButton) {
    
      let i : Int = (sender.layer.valueForKey("index")) as! Int
      userNames.removeAtIndex(i)
      UserSelectCollection.reloadData()
    }
    

Many thanks to JigarM for his examples on GitHub: https://github.com/JigarM/UICollectionView-Swift




回答2:


Why not create custom UICollectionViewCell in IB and just add button to it ? Register it to your collectionView with :

- registerNib:forCellReuseIdentifier:

You can use delegate or notification to process button tap.



来源:https://stackoverflow.com/questions/29610316/how-to-add-a-delete-button-to-collection-view-cell-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!