在Swift 4中单击单元格时,如何在CollectionView外部更改textLabel?

问题描述

当我单击单元格时,如何帮助我更改在CollectionView外部但在同一ViewController中的标签中的文本?我需要标签中具有不同单元格的不同文本。

P.S。我是新手:)

解决方法

在单元格的didSelectAt函数中,您可以基于该indexPath检索另一个单元格,然后可以更新该单元格中的标签:

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        let otherCell = collectionView.cellForItem(at: IndexPath(item: otherCellsIndexItem,section: otherCellsIndexSection)) as! YourCollectionViewCell
        otherCell.label.text = "New Text"
        }
    }

编辑1:标签位于集合视图之外,然后:

class YourView {
  ...
  @IBOutlet weak var yourLabel: UILabel!
  // or
  var yourLabel: UILabel?

  ...
  func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        self.label.text = "New Text"
        // or,if it's UILabel?,then:
        self.label?.text = "New Text"
        }
    }
}