将多个参数传递给addTarget

Art*_*rti 10 uitableview ios swift

在我的UITableViewCell我有一个按钮.我想通过在cellForRowAtIndexPath方法中传递多个参数来添加操作.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:
        indexPath) as! CartTableViewCell
    cell.buyButton.addTarget(self, action: self.buyButton(indexPath, 2, 3 ,4 , 5, 6), forControlEvents: .TouchUpInside)
}
Run Code Online (Sandbox Code Playgroud)

Ank*_*hah 39

也许你可以做这样的事情

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)
}
Run Code Online (Sandbox Code Playgroud)

根据您的要求创建标签值,并保持其完整性.


小智 11

如果你需要传递字符串,只需使用UIButton的accessibilityHint.

Tag只能存储Int,所以如果有人想传递字符串数据就可以使用它.但是,这不是传递数据的正确方法!

例:

button.accessibilityHint = "your string data"
button.addTarget(self, action: Selector(("buttonTapped")), for: UIControlEvents.touchUpInside)

func buttonTapped (sender: UIButton) {
   let section = sender.accessibilityHint
}
Run Code Online (Sandbox Code Playgroud)


she*_*tal 8

我认为我们应该很好地构建代码.黑客只会使你的代码难以理解和错误.这是一些建议.

制作自定义按钮类

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!
}}
Run Code Online (Sandbox Code Playgroud)

现在将目标添加到按钮

let btn = your custom button
btn.name = “Your name”
btn.object = any object
btn.addTarget(self, action: #selector(myMethod(_:)), forControlEvents:.TouchUpInside)
Run Code Online (Sandbox Code Playgroud)

现在只需在方法调用中获取您的值

  @IBAction func myMethod(sender:CustomButton) {
    print(sender.name)
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 6

简单!

1:子类UIButton:

class IndexPathCellButton: UIButton {
    var indexPath:NSIndexPath?
}
Run Code Online (Sandbox Code Playgroud)

2:设定你的价值:

...
cell.indexPathButton.addTarget(self, action: #selector(LocationSearchViewController.cellOptionButtonClick(_:)), forControlEvents: .TouchUpInside)
cell.indexPathButton.indexPath = indexPath // Your value
...
Run Code Online (Sandbox Code Playgroud)

3:检索你的价值:

@objc private func cellOptionButtonClick(sender: IndexPathCellButton) {
    print(sender.indexPath)
}
Run Code Online (Sandbox Code Playgroud)