[英]Custom tap recognizer method won’t work if implemented in other class
(我是個速成的初學者)
上下文/我要實現的目標:
由於我將在各種視圖中使用很多輕敲識別器(用於標簽和imageViews),因此我想創建一個默認方法,該方法可在每次需要輕敲識別器時幫助我節省幾行代碼。
->我想要的例子
class Toolbox {
static func customTapRecognizerForLabel () {}
static func customTapRecognizerForImage () {}
}
所以我可以在不同的視圖控制器中使用它們:
class ViewControllerOne{
Toolbox.customTapRecognizerForLabel()
}
class ViewControllerTwo{
Toolbox.customTapRecognizerForLabel()
}
到目前為止,我做了什么?:
無效的方法:我在Toolbox.swift中創建了Toolbox類,試圖在其他視圖控制器中調用它,但是它不起作用。 (也嘗試定義類的共享實例,而不是使用靜態方法,但是也沒有用)
有效的方法:在同一視圖控制器中實現方法。
我的工具箱代碼:
import Foundation
import UIKit
class Toolbox: UIViewController {
static func tapRecognizerforLabel (named label: UILabel, action: Selector) {
let tapGestureForLabel = UITapGestureRecognizer(target: self, action: action)
label.addGestureRecognizer(tapGestureForLabel)
label.isUserInteractionEnabled = true
}
}
我怎么稱呼它:
class ViewOne: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
Toolbox.tapRecognizerforLabel(named: nameLabel, action: #selector(self.methodAlpha))
}
func methodAlpha() {
print("It's friday my dudes")
}
}
觸摸標簽時收到的錯誤:
2018-07-13 11:08:22.131602-0500 MyApp[20435:1274296]
+[MyApp.Toolbox methodAlpha]: unrecognized selector
sent to class 0x1033c0038
2018-07-13 11:08:22.218289-0500 MyApp[20435:1274296]
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason:
'+[MyApp.Toolbox methodAlpha]: unrecognized selector
sent to class 0x1033c0038'
如果我在ViewOne類中實現了tapRecognizerforLabel()方法,但在其他類中卻實現了它,為什么不起作用?
歡迎以其他方式實現我想要的建議
謝謝 :)
您需要像這樣發送目標
func tapRecognizerforLabel (named label: UILabel, action: Selector,target:Any) {
let tapGestureForLabel = UITapGestureRecognizer(target:target, action: action)
label.addGestureRecognizer(tapGestureForLabel)
label.isUserInteractionEnabled = true
}
目標應該包含選擇器內部方法的實現,因為您將self
設置為Toolbox
並且其中不包含它,因此發生崩潰,要調用
Toolbox.tapRecognizerforLabel(named: nameLabel, action: #selector(self.methodAlpha),target:self)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.