swift - 我可以在 Swift 4 中将参数(不是发件人)附加到 uiButton.addTarget
问题描述
我是 iOS 开发的新手。请检查以下代码。
let dropDown = DropDown()
override func viewDidLoad() {
super.viewDidLoad()
dropDown.anchorView = dropDownTest // UIView or UIBarButtonItem
dropDown.dataSource = ["Car", "Motorcycle", "Truck"]
dropDown.bottomOffset = CGPoint(x: 0, y:(dropDown.anchorView?.plainView.bounds.height)!)
dropDownTest.addTarget(self, action: #selector(self.buttonClicked(sender:)), for: .touchUpInside)
}
@objc private func buttonClicked(sender: UIButton) {
dropDown.show()
}
这很容易,因为dropDown
可以从buttonClicked
方法调用变量。但是,就我而言,我必须在与表格单元相关的方法中执行此操作cellForRowAt
。
let cell = tableView.dequeueReusableCell(withIdentifier: "VarientCell", for: indexPath)
let varientButtonTag = 1
let varientButton = cell.viewWithTag(varientButtonTag) as! UIButton
let varientDropDown = DropDown()
varientDropDown.anchorView = varientButton
varientDropDown.dataSource = datasource
varientDropDown.bottomOffset = CGPoint(x: 0, y: varientButton.bounds.height)
varientButton.addTarget(self, action: #selector(self.varientButtonClicked(sender:)), for: .touchUpInside)
return cell
和按钮单击方法,
@objc private func varientButtonClicked(sender: UIButton) {
//dropDown.show()
// my problem is here.., i need to pass the dropDown somehow to show that.
}
解决方案
有很多方法可以做到这一点。我指的是两种可能的方法。1. 您可以继承 UIButton 并为其设置参数。
class MyButton: UIButton{
var myParam1: String?
var myParam2: String?
}
创建自定义表格视图单元格并处理里面的按钮调用
导入 UIKit
class MyCell: UITableViewCell{ @IBOutlet weak var myButton: UIButton! @IBOutlet weak var anotherButton: UIButton! func setup(model: YourDataModel){ myButton.addTarget(self, action:#selector(self.didSelect(_ :), for: .touchUpInside) anotherButton.addTarget(self, action: #selector(self.didSelect(_ :)), for: .touchUpInside) } @objc func didSelect(_ sender: UIButton){ switch sender { case myButton: print("my button clicked") case anotherButton: print("anotherButton clicked") default: break } } }
推荐阅读
- flutter - NoSuchMethodError:在 null 上调用了方法“[]”。颤动本地json文件
- python - UnboundLocalError: local variable.... 赋值前引用
- java - Android Studio TextView 文本选择处理程序图标位置
- c# - 如何同步调用或等待异步回调完成?
- python - 获取 python 退出状态并在 bash 命令中使用它
- reactjs - 哈希路由器和浏览器路由器出错。女巫 gh-pages
- reactjs - 父组件如何与作为 prop 传入的子组件通信?
- android - 重启广播接收器不工作 Infinix android 10 设备
- excel - Power Query Excel - 根据其他行值更新行
- axis - 在 wsdltojava 生成的类中面临编译错误