ios - 使用带有多个参数的 @objc 委托方法
问题描述
我希望能够将多个参数传递给一个#selector()
方法,而不仅仅是发送者本身。
说,我有一个UITextField
which 有一个UITapGestureRecognizer
,我希望其他班级成为 this 的代表UITapGestureRecognizer
。我为它编写了一个委托协议,称为SomeDelegateProcotol
. 但是,我还想在点击时将 UITextField 的实例传递给委托。我想事情可能看起来像这样:
// The delegate
class Delegate: SomeDelegateProcotol {
private let textField = TextField()
func handleTapFromView(_ sender: UITapGestureRecognizer, textField: UITextField) {
print("Hey! I should handle the tap from the user.")
}
init() {
textField.delegate = self
}
}
// The protocol
@objc protocol SomeDelegateProtocol {
@objc func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var delegate: SomeDelegateProtocol?
override init(frame: CGSize) {
super.init(frame: frame)
...
let gestureRecognizer = UITapGestureRecognizer(target: delegate!,
action: #selector(delegate!.handleTapFromView(_:, textField:
self)))
}
}
但是,这不是正确的语法,因为handleTapFromView(_:, textField: self)
它是无效的。这引发了以下我尚未找到解决方案的问题:
- 这种语法到底是什么意思?
(_:)
. 我假设它正在传递自己,但UITapGestureRecognizer
尚未创建? - 如何成功地将 TextField 实例传递给发送者旁边的委托?
解决方案
I would suggest keeping things as simple as this,
protocol SomeDelegateProtocol: class {
func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var someDelegate: SomeDelegateProtocol?
override init(frame: CGRect) {
super.init(frame: frame)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func tap(_ sender: UITapGestureRecognizer) {
self.someDelegate?.handletapFromView(sender, textField: self)
}
}
推荐阅读
- php - 如何在特定日期时间到秒执行一些代码?
- javascript - javascript检查和打开页面
- sockets - ACE - 是否可以使用快速路径创建管道?
- django - 为什么我会得到不同的结果?
- jenkins - 如何在 DSL 脚本中嵌入 jenkins 管道
- reactjs - 在 React 中动画显示/隐藏表格行
- java - 单击时更改视图高度
- python - Karger 在 python 2.7 中的最小切割实现没有给出正确的切割
- c# - 仅将选定的列更改为自定义格式,而所有列在 WPF DataGrid 中保持不变?
- sql-server - 将数据插入另一个表时数据类型格式发生变化 (MICROSOFT SQL Server Management Studio)