Search code examples
ioslabelswift4cellcollectionview

How to change textLabel outside CollectionView when cell is clicked in Swift 4?


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 :)


Solution

  • 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"
            }
        }
    }