user4720432
user4720432

Reputation:

How to pass a Parameter to the addTarget method of button in swift

I have a CollectionViewCell and i am working on cellForItemAt method of it. I have a button in each Collection view cell which defines to 3 different section in my CollectionView.

I am adding below code to set the button target: cell.buttonView.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControlEvents.touchUpInside)

Now, i have created a new method: @objc func buttonPressed(sender: UIButton) where i am adding a title to the UIAlertController like: let alertController = UIAlertController(title: , message: "Below actions are", preferredStyle: .actionSheet)

So basically, each time any button is tapped in the cell, the Alert should open and also each time the title will be different for it.

How do i pass the title here dynamically?

Upvotes: 0

Views: 3313

Answers (1)

Nancy Madan
Nancy Madan

Reputation: 447

If the title to be passed is button's title, then you can simply do this :-

@objc func buttonPressed(sender: UIButton){
let title = sender.title(for: .normal)
}

And if it is some other data in section, you can use tags on your buttons, and setting them to indexPath.row :-

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.buttonView.tag = indexPath.row
}

And in your Button's action, access button's tag

    @objc func buttonPressed(sender: UIButton){
        let objectIndex = sender.tag
        let object = yourArray[objectIndex]
let title = object.title
        }

Upvotes: 4

Related Questions