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

Mar*_*sor 2 ios uicollectionview swift swift3

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

在 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")
            }
          }
Run Code Online (Sandbox Code Playgroud)

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

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

    }
Run Code Online (Sandbox Code Playgroud)

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

Mo *_*eed 5

您可以像这样使用tag属性UIButton

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

cell.commentButton.tag = (indexPath.section * 100) + indexPath.item
Run Code Online (Sandbox Code Playgroud)

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

cell.commentButton.addTarget(self, action: #selector(editPostAction(sender:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

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

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()
}
Run Code Online (Sandbox Code Playgroud)