如何在Swift中向Collection View Cell添加删除按钮?

时间:2015-04-13 16:25:13

标签: ios swift uicollectionview uicollectionviewcell

现在我有一个滚动用户名列表,使用按钮的集合视图。但我想为每一行添加重叠的删除按钮。它们需要附加到名称按钮并随之滚动。

如何将这些按钮添加到我的CollectionView? (我还想跳过第一行的删除按钮,原因很明显)

User Selection Screen

当前代码:

  //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)
    }

  }

2 个答案:

答案 0 :(得分:14)

搞定了!以下是:

  1. 我在故事板中为单元格添加了一个按钮。
  2. 将插座连接到UICollectionViewCell类。
  3. 编辑视图控制器代码:

    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()
    }
    
  4. 非常感谢JigarM在GitHub上的例子: https://github.com/JigarM/UICollectionView-Swift

答案 1 :(得分:1)

为什么不在IB中创建自定义UICollectionViewCell并只添加按钮呢? 将其注册到您的collectionView:

- registerNib:forCellReuseIdentifier:

您可以使用委托或通知来处理按钮点击。