将多个parameter passing给addTarget
在我的UITableViewCell
我有一个button。 我想通过在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) }
也许你可以做这样的事情
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) }
根据你的要求创build标签值,维护它的完整性。
如果你需要传递string,只需使用UIButton的accessibilityHint即可。
标签只能存储Int,所以如果有人想传递string数据可以使用这个。 但是,这不是传递数据的正确方法!
例:
button.accessibilityHint = "your string data" button.addTarget(self, action: Selector(("buttonTapped")), for: UIControlEvents.touchUpInside) func buttonTapped (sender: UIButton) { let section = sender.accessibilityHint }
我认为我们应该很好地构build代码。 黑客只会让你的代码很难理解和越野车。 这是一些build议。
制作一个自定义的button类
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! }}
现在将目标添加到您的button
let btn = your custom button btn.name = “Your name” btn.object = any object btn.addTarget(self, action: #selector(myMethod(_:)), forControlEvents:.TouchUpInside)
现在只需在方法调用中获取您的值
@IBAction func myMethod(sender:CustomButton) { print(sender.name) }
简单!
1:子类UIButton
:
class IndexPathCellButton: UIButton { var indexPath:NSIndexPath? }
2:设置你的值:
... cell.indexPathButton.addTarget(self, action: #selector(LocationSearchViewController.cellOptionButtonClick(_:)), forControlEvents: .TouchUpInside) cell.indexPathButton.indexPath = indexPath // Your value ...
3:检索你的价值:
@objc private func cellOptionButtonClick(sender: IndexPathCellButton) { print(sender.indexPath) }
您可以使用UIButtons的titleLabel
和UIImageView
上的tag
属性来添加其他参数
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) }