In my UITableViewCell
I have a button. And I want to add action to it by passing multiple parameters in cellForRowAtIndexPath
method.
Easy!
1: Subclass UIButton
:
class IndexPathCellButton: UIButton {
var indexPath:NSIndexPath?
}
2: Set your value:
...
cell.indexPathButton.addTarget(self, action: #selector(LocationSearchViewController.cellOptionButtonClick(_:)), forControlEvents: .TouchUpInside)
cell.indexPathButton.indexPath = indexPath // Your value
...
3: Retrieve your value:
@objc private func cellOptionButtonClick(sender: IndexPathCellButton) {
print(sender.indexPath)
}
May be you can do something like this
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:indexPath) as! CartTableViewCell
cell.buyButton.tag = (indexPath.section*100)+indexPath.row
cell.buyButton.addTarget(self, action: "btnBuy_Click:", forControlEvents: .TouchUpInside)
}
func btnBuy_Click(sender: UIButton) {
//Perform actions here
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.buyButton(indexPath, 2, 3 ,4 , 5, 6)
}
Create tag value according to you'r requirement and maintaint it's integrity too.
I think we should architect the code well. The hacks will just make your code hard to understand and buggy. Here is some suggestion.
Make a custom button class
class CustomButton:UIButton {
var name:String = ""
var object:MyObjectClassType?
convenience init(name: String, object: MyObjectClassType) {
self.init(frame:CGRectZero)
self.name =name
self.object = object!
}}
Now add target to your button
let btn = your custom button
btn.name = “Your name”
btn.object = any object
btn.addTarget(self, action: #selector(myMethod(_:)), forControlEvents:.TouchUpInside)
Now simply get your values in the method call
@IBAction func myMethod(sender:CustomButton) {
print(sender.name)
}
If you need to pass string just use accessibilityHint of UIButton.
Tag can only store Int so if anyone wants to pass string data can use this. However, this not a proper way of passing data!
example:
button.accessibilityHint = "your string data"
button.addTarget(self, action: Selector(("buttonTapped")), for: UIControlEvents.touchUpInside)
func buttonTapped (sender: UIButton) {
let section = sender.accessibilityHint
}
You can use the tag
property on the UIButtons's titleLabel
and UIImageView
to add additional parameters
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:indexPath) as! CartTableViewCell
cell.buyButton.tag = (indexPath.section*100)+indexPath.row
cell.buyButton.imageView.tag = 2
cell.buyButton.titleLabel.tag = 3
cell.buyButton.addTarget(self, action: "btnBuy_Click:", forControlEvents: .TouchUpInside)
}