ios - 在UICollectionViewCell中使用Button编辑难点

标签 ios swift uibutton uicollectionviewcell

我实现了一个编辑按钮,它向我的 UICollectionViewCell 添加了一个按钮。当我按下编辑 => 编辑变成“完成”时,当我按下完成时,它应该删除按钮。 我的代码允许我添加按钮,但不隐藏它们。 有什么想法吗?

 @IBAction func editButton(sender: AnyObject) {

if(editButton.titleLabel?.text as String! == "Edit")
  {

    editButton.setTitle("Done", forState: UIControlState.Normal)
    for item in self.mainCollectionView.visibleCells() as! [SettingsCollectionViewCell] {

        let indexpath : NSIndexPath = self.mainCollectionView!.indexPathForCell(item as SettingsCollectionViewCell)!
        let cell : SettingsCollectionViewCell = mainCollectionView!.cellForItemAtIndexPath(indexpath) as! SettingsCollectionViewCell

        //Close Button
        let close : UIButton = cell.collectionViewButton
        close.hidden = false
    }
} 
else 
{
    editButton.setTitle("Edit", forState: UIControlState.Normal)
    self.mainCollectionView?.reloadData()
 }}

cellForRowAtIndexPath:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
     {

    let collectionCell:SettingsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as! SettingsCollectionViewCell

      if self.editButton.titleLabel?.text as String! == "Edit" 
        {
          collectionCell.collectionViewButton.hidden = true
        }
     else if editButton.titleLabel?.text as String! == "Done"
        {
         collectionCell.collectionViewButton.hidden = false
        }

        collectionCell.collectionViewButton!.layer.setValue(indexPath.row, forKey: "index")
        collectionCell.collectionViewButton!.addTarget(self, action: "deletePhoto:", forControlEvents: UIControlEvents.TouchUpInside)

        return collectionCell
}

最佳答案

您需要更改 cellForItemAtIndexPath 中的逻辑以从按钮中检索标题。

为了从按钮中检索标题文本,您需要使用 titleForState(UIControlState) 而不是 titleLabel?.text

这是 cellForItemAtIndexPath 中条件语句的代码片段

if self.editButton.titleForState(.Normal) == "Edit" {
       collectionCell.collectionViewButton.hidden = true
}
else if self.editButton.titleForState(.Normal) == "Done" {
    collectionCell.collectionViewButton.hidden = false
}

关于ios - 在UICollectionViewCell中使用Button编辑难点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463897/

相关文章:

ios - 为 UIControlStateHighlighted 设置 UIImage

ios - 如何向 UIButton 操作添加 UIAccessibility 功能?

ios - 将 PHAsset 从 Gallery 复制到 iOS 9 中的其他目录

ios - 按 Realm 排序(字母、数字、特殊字符)

ios - 开头的函数返回值

ios - 我需要在 deinit 中删除 UIGestureRecognizer 吗?

ios - Realm add 不会插入所有对象

ios - 在 AppDelegate 启动时访问 Root View Controller

ios - 后台的 Swift 定时器

ios - 使 View 变暗,就像禁用一样