-1

can you help me how can I change text in label, which is outside the CollectionView but in the same ViewController, when cell is clicked? I need different text in label with different cell.

P.S. I'm new in swift :)

ifF3
  • 31
  • 9

1 Answers1

0

In the cell's didSelectAt function you can retrieve the other cell based on that indexPath and then you can update the label in that cell:

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

EDIT 1: The label is outside the collection view, then:

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"
        }
    }
}
zdtorok
  • 594
  • 1
  • 7
  • 21
  • But Label isn't in any cell, it's outside, in viewController. – ifF3 Oct 07 '20 at 09:46
  • In this case I guess you have it as an IBOutlet or simply variable in your class. So, simply access that and change the text. See my edit. – zdtorok Oct 07 '20 at 09:53