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

浪尽此生 提交于 2019-11-30 07:37:49

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

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.

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