retrieve the 'title' value of a button

0
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let identifier = "item"

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CollectionViewCell
        //print("Posicion" , indexPath)
        cell.btnCollection.setTitle(String(describing: indexPath), for: UIControlState.normal)
        cell.btnCollection.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        return cell
    }

I'm creating a button and assign a value as a title in this way

cell.btnCollection.setTitle(String(describing: indexPath), for: UIControlState.normal)

and at the same time I assign a click action to each button

cell.btnCollection.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

and the function that is executed when clicking on the buttons is as follows

 @objc func buttonAction(sender: UIButton!) {
        //var Alert = UIAlertController(title:"Alert",message: "dsdsd" , preferredStyle: UIAlertControllerStyle.alert)
        //self.present(Alert, animated: true, completion: nil)
        sender.backgroundColor = UIColor.red
    }

I would like to know how I can recover the "title" value of the button I press and show it in the Alert

    
asked by Ernesto Emmanuel Yah Lopez 01.02.2018 в 12:50
source

1 answer

0

You can get the button title with the title(for:) method.

Here you can see the documentation (in English), it says:

  

Returns the title associated with the specified state.

that is:

  

Returns the title associated with the specified state.

In your code:

@objc func buttonAction(sender: UIButton!) {
    if let title = sender.title(for: .normal) {
        // hacer algo con "title"
    }
    ...
}

Another option is to use a tag for each button, and ask for tag instead of the title.

    
answered by 01.02.2018 / 13:25
source