在UICollectionView单元格中隐藏按钮

时间:2016-09-12 20:43:23

标签: ios swift swift2 uicollectionview

我以编程方式创建单元格并为每个单元格添加删除按钮。问题是我想切换他们的.hidden状态。我们的想法是拥有一个编辑按钮,可以同时切换所有按钮的状态。也许我会以错误的方式解决这个问题?

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("verticalCell", forIndexPath: indexPath) as! RACollectionViewCell
    let slide = panelSlides[indexPath.row]
    cell.slideData = slide
    cell.slideImageView.setImageWithUrl(NSURL(string: IMAGE_URL + slide.imageName + ".jpg")!)
    cell.setNeedsLayout()

    let image = UIImage(named: "ic_close") as UIImage?
    var deleteButton = UIButton(type: UIButtonType.Custom) as UIButton
    deleteButton.frame = CGRectMake(-25, -25, 100, 100)
    deleteButton.setImage(image, forState: .Normal)
    deleteButton.addTarget(self,action:#selector(deleteCell), forControlEvents:.TouchUpInside)
    deleteButton.hidden = editOn
    cell.addSubview(deleteButton)
    return cell
}


@IBAction func EditButtonTap(sender: AnyObject) {
    editOn = !editOn
    sidePanelCollectionView.reloadData()
}

1 个答案:

答案 0 :(得分:1)

我认为您要做的是按索引迭代所有数据,然后针对每个索引在cellForItemAtIndexPath:上调用UICollectionView。然后,您可以将该现有单元格转换为特定类型as? RACollectionViewCell,然后以这种方式设置按钮隐藏值。

示例(道歉我现在没有在xcode中对此进行精确验证,但这是要点):

for (index, data) in myDataArray.enumerated() {
   let cell = collectionView.cellForRowAtIndexPath(NSIndexPath(row: index, section: 0)) as? RACollectionViewCell
   cell?.deleteButton.hidden = false
}

您可能还需要在视图控制器中使用某种isEditing布尔变量来跟踪您处于编辑状态的事实,以便在滚动时,新配置的单元格继续显示/不显示按钮。您将需要上面的现有代码,以确保它在滚动发生时继续工作。您不应每次都创建新的删除按钮,而应将按钮放在故事板中并设置参考,然后您可以使用类似cell.deleteButton.hidden = !isEditing

的内容