title: Swift 4: When a user clicks on a UiButton how do I grab the string that is selected in a UICollectionView?
body: <p>Question: I am trying to know which town someone selected when they clicked on a UIButton. When the user clicks on the UIButton I want to be able to know the "name" of which townName the user selected. How can I do this? I was able to pass the indexPath.row successfully but I am not sure how to pass the name of the town the user selected. This is my code below. Would love any help on this!</p>
  
  <pre><code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TownCell
      let name = townName[indexPath.row].name
      let regionId = townName[indexPath.row].region_code
  
      cell.townLabel.text = "\(name), \(regionId)"
  
      cell.button.tag = indexPath.row
      print(townName[indexPath.row].name)
      print(townName[indexPath.row].region_code)
      return cell
  }
  
  
      lazy var button: UIButton = {
          let button = UIButton(type: .system)
          button.backgroundColor = greenCTAColor
          button.layer.cornerRadius = 15
          button.setTitle("select", for: .normal)
          button.setTitle("selected", for: .selected)
          button.setTitleColor(.white, for: .normal)
          button.setTitleColor(.white, for: .selected)
          button.tintColor = .clear
          button.titleLabel?.font = UIFont(name: "ProximaNova-Semibold", size: 16)
          button.addTarget(self, action: #selector(selectedAction), for: .touchUpInside)
          return button
      }()
  
      @objc func selectedAction(sender: AnyObject) {
          let currentCellNumber = sender.tag
          if let button = sender as? UIButton {
              if button.isSelected {
                  button.isSelected = false
                  button.backgroundColor = greenCTAColor
                  print("User unselected cell number: \(currentCellNumber!)")
              } else {
                  button.isSelected = true
                  button.backgroundColor = blueCTAColor
                  print("User selected cell number: \(currentCellNumber!)")
              }
          }
      }
  </code></pre>