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

标签 ios swift uicollectionview uicollectionviewcell

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

如何将这些按钮添加到我的 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)
    }

  }

最佳答案

成功了!方法如下:

  1. 我在 Storyboard 的单元格中添加了一个按钮。
  2. 将 socket 连接到 UICollectionViewCell 类。
  3. 将 View Controller 代码编辑为:

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

非常感谢 JigarM 在 GitHub 上提供的示例: https://github.com/JigarM/UICollectionView-Swift

关于ios - 如何在 Swift 中向 Collection View Cell 添加删除按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610316/

相关文章:

ios - 在条形码扫描仪应用程序 (Swift 3) 中的相机 View 上添加对象

ios - 需要帮助将新的存储属性添加到 UITableView

iphone - 从 IO 单元将音频写入磁盘

swift - searchBarSearchButtonClicked 不工作 swift

ios - 在 Swift 中为 XCTest 进行模拟

ios - 禁用滚动时如何确定 UICollectionView 宽度

ios - DidSelectItemAtIndexPath 不适用于 collectionview

ios - 自定义导航栏项目放置不当

ios - 动态表格 View 单元格,以编程方式更改 subview 高度

ios - 如何为我的 CollectionView 单元格提供 onclick 功能?