UICollectionView 自定义单元格访问单元格外的属性

Posted

技术标签:

【中文标题】UICollectionView 自定义单元格访问单元格外的属性【英文标题】:CollectionView Custom Cell accessing atributes outside of the cell 【发布时间】:2017-06-24 14:28:54 【问题描述】:

我正在尝试在单元格外部的集合视图中更改自定义视图单元格的一些属性,但我无法弄清楚我做错了什么:

在 cellForItem 我有:

          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PatientProfileCell", for: indexPath) as! PatientQuestionCell

                if Auth.auth().currentUser?.uid == userID 
                  cell.commentButton.setTitle("Edit post", for: .normal)
                  cell.commentButton.addTarget(self, action: #selector(editPostAction), for: .touchUpInside)
                
             else 
                print("Not the current user for collection view")
            
          

这里一切正常,但是当我触发动作时,什么也没有发生。这是函数:

  //post actions
    func editPostAction()  
        print("Edit post Enabled")

        let cell = PatientQuestionCell()

        cell.questionView.isEditable = true
        cell.questionView.isSelectable = true
        cell.questionView.isScrollEnabled = true
        cell.questionView.becomeFirstResponder()

    

如何使用此功能更改单元格的属性?

【问题讨论】:

函数是否打印“Edit post Enabled”? 是的!带有单元格的另一部分不起作用 您的目标是更改您单击其按钮的单元格中的那些属性,对吧? 是的!我没有做 indexPath 不是吗?我正在努力实现无法实现的目标:) 您正在分配一个新的单元格实例并对其进行修改,而不是包含按钮的单元格。请参阅this,它是关于表格视图的,但该方法也适用于集合视图。请注意,由于单元格重用,您当前的代码将多次将操作处理程序添加到多个单元格 【参考方案1】:

您可以像这样使用UIButtontag 属性:

在您的 collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 方法中,添加这行代码:

cell.commentButton.tag = (indexPath.section * 100) + indexPath.item

然后像这样设置按钮的目标:

cell.commentButton.addTarget(self, action: #selector(editPostAction(sender:)), for: .touchUpInside)

现在,添加一个新方法,即您的选择器:

func editPostAction(sender: UIButton) 
    let section = sender.tag / 100
    let item = sender.tag % 100
    let indexPath = IndexPath(item: item, section: section)

    let cell = self.collectionView?.cellForItem(at: indexPath) as! PatientQuestionCell
    cell.questionView.isEditable = true
    cell.questionView.isSelectable = true
    cell.questionView.isScrollEnabled = true
    cell.questionView.becomeFirstResponder()

【讨论】:

谢谢你,这很好用!你能告诉我函数中的 100 是什么,以便我更好地理解它的作用吗? 不客气。这只是一种了解按钮所属单元格的方法。例如,第 2 部分中的第 5 个单元格的标记等于:(2 * 100) + 5 = 205。现在:部分 = 205 / 100 = 2(整数除法)。并且项目 = 205 % 100 = 5。 这个答案的灵感来自一个与表格视图相关的类似问题,我在 *** 上找到了答案,但我找不到它的链接。 这真是太聪明了!谢谢你。 主题:我想知道您是否对此有所了解,它与同一主题有某种关系:***.com/questions/44740910/…

以上是关于UICollectionView 自定义单元格访问单元格外的属性的主要内容,如果未能解决你的问题,请参考以下文章

UICollectionView - 连接到自定义单元格

UICollectionView 椭圆形自定义单元格

如何使用 2 个或更多自定义单元格创建自定义 UICollectionView?

如何在 UICollectionView 中有自定义单元格

UICollectionView 自定义单元格未重新加载

UICollectionView 单元格的自定义委托 - 自定义按钮不起作用