[英]iOS Swift: Send action (control event) from subclass of UIImageView
How can I send action (similar kind of tap event) from sub class of UIImageView to View Controller.如何从 UIImageView 的子 class 发送动作(类似类型的点击事件)到查看 Controller。
Here is reference answer , that I want to apply for UIImageView.这是参考答案,我想申请UIImageView。 (UIImageView does not have UIControl in its super class hierarchy)
(UIImageView 在其超级 class 层次结构中没有 UIControl)
Following is my code but not working as I don't know, how to implement, what I need.以下是我的代码,但由于我不知道如何实现,我需要什么而无法正常工作。
class TappableImageView: UIImageView {
// Initializer methods.....
//------------------------------------------
private func addTapGesture(){
let tapOnImage = UITapGestureRecognizer(target: self, action: #selector(TappableImageView.handleTapGesture(tapGesture:)))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapOnImage)
}
//----------------------------------------------
@objc func handleTapGesture(tapGesture: UITapGestureRecognizer) {
// how can I send tap/click event to all view controllers, where I've used this image from this point.
}
}
Is there any alternate/other solution that may work for me?是否有任何替代/其他解决方案可能对我有用?
I will recommend you to use a closure to handle taps:我会建议你使用闭包来处理水龙头:
class TappableImageView: UIImageView {
var handleTap: (() -> Void)? = nil
//------------------------------------------
private func addTapGesture(){
let tapOnImage = UITapGestureRecognizer(target: self, action: #selector(TappableImageView.handleTapGesture(tapGesture:)))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapOnImage)
}
//----------------------------------------------
@objc func handleTapGesture(tapGesture: UITapGestureRecognizer) {
handleTap?()
}
}
And then I your view controller you can use this ie in viewDidLoad
method:然后我你的观点 controller 你可以在
viewDidLoad
方法中使用它:
override func viewDidLoad() {
super.viewDidLoad()
yourTappableImageView.handleTap = {
print("an image view was tapped")
}
}
It assumes that your TappableImageView
is stored in variable named yourTappableImageView
.它假定您的
TappableImageView
存储在名为yourTappableImageView
的变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.