我在SKScene中设置了滑动识别,我发现硬编码所有识别器需要时间并且不是很整洁,所以我决定使用for循环和包含{{的字典1}}作为键,UISwipeRecognizer
作为值。问题是,在尝试使用()
以下是代码:
recognizer.addTarget(self, action: #selector(functionForRecognizer[recognizer]!))
}
顺便说一句,我试图在声明功能的同时放class xxxxx: SKScene {
let rightSwipeRecognizer = UISwipeGestureRecognizer()
let leftSwipeRecognizer = UISwipeGestureRecognizer()
let upSwipeRecognizer = UISwipeGestureRecognizer()
let downSwipeRecognizer = UISwipeGestureRecognizer()
var swipeRecognizers: [UISwipeGestureRecognizer] {
return [rightSwipeRecognizer, leftSwipeRecognizer, upSwipeRecognizer, downSwipeRecognizer]
}
var directionForRecognizer: [UISwipeGestureRecognizer : UISwipeGestureRecognizerDirection] {
return [
rightSwipeRecognizer : .right,
leftSwipeRecognizer : .left,
upSwipeRecognizer : .up,
downSwipeRecognizer : .down
]
}
func didSwipeRight() {}
func didSwipeLeft() {}
func didSwipeUp() {}
func didSwipeDown() {}
var functionForRecognizer: [UISwipeGestureRecognizer : ()] {
return [
rightSwipeRecognizer : didSwipeRight(),
leftSwipeRecognizer : didSwipeLeft(),
upSwipeRecognizer : didSwipeUp(),
downSwipeRecognizer : didSwipeDown()
]
}
func setupSwipeRecognizers() {
for recognizer in swipeRecognizers {
recognizer.addTarget(self, action: #selector(functionForRecognizer[recognizer]!))
recognizer.direction = directionForRecognizer[recognizer]!
self.view?.addGestureRecognizer(recognizer)
}
}
override func didMove(to view: SKView) {
super.didMove(to: view)
setupSwipeRecognizers()
}
,但它没有用。此外,我尝试通过从SKScene中删除继承并符合NSObject来将类暴露给NSObject,但它仍然无法工作。此外,我不能将类与UIKit类相符合,cz我需要它作为SKScene,甚至,我尝试将它符合UIViewController(当然没有SKScene),但仍然没有工作,
答案 0 :(得分:4)
Swift的#selector
无法实现您的目标。而是将Selector
类的实例直接插入字典中。
您还需要使用@objc
进行注释@objc // This annotation isn't required in Swift 3, but will be in Swift 4
func didSwipeRight() {}
var functionForRecognizer: [UISwipeGestureRecognizer : Selector] {
return [
rightSwipeRecognizer : #selector(didSwipeRight)
]
}
recognizer.addTarget(self, action: functionForRecognizer[recognizer]))
有关#selector
的详细说明,请参阅this answer。总结,#selector
是Swift的编译器构造,它确保存在精确的选择器/方法,包括它应该存在的类。它查看括号内的实际内容以查看它是否是已知方法,functionForRecognizer[recognizer]
不是方法名称,它是变量+下标方法调用。