我正在尝试将UIGestureRecognizer集成到我的快速游乐场中,这样无论我在操场上点什么,我的精灵就会到达那一点。我已经尝试了一切!观看无数的youtube视频,然后进行堆栈溢出以获得答案,但每个人都开始创建一个名为视图的类,这是一个UIView,在他们的代码中他们一直指的是“自我”。我做了一个名为“view”的变量,它是一个SKView。我尝试获取部分代码,将其放入我的代码中并进行更改,但它只是不起作用。这是我到目前为止的工作。
view.addGestureRecognizer(UIGestureRecognizer(target: view, action: #selector(handleTap(sender:))))
func handleTap(sender: UITapGestureRecognizer) {
player.position = sender.location(in: view)
}
我的游乐场一直告诉我,我正在使用未解析的标识符'handleTap(sender :)'
答案 0 :(得分:2)
UIGestureRecognizer示例,在Playground中具有不同的手势识别器状态
<强> swift3 + 强>
导入UIKit 导入PlaygroundSupport
类ViewController:UIViewController {
var yellowView: UIView!
var redView: UIView!
var yellowViewOrigin: CGPoint!
override func loadView() {
// UI
let view = UIView()
view.backgroundColor = .white
yellowView = UIView()
yellowView.backgroundColor = .yellow
view.addSubview(yellowView)
redView = UIView()
redView.backgroundColor = .red
view.addSubview(redView)
// Layout
redView.translatesAutoresizingMaskIntoConstraints = false
yellowView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0),
yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
yellowView.heightAnchor.constraint(equalToConstant: 80.0),
yellowView.widthAnchor.constraint(equalToConstant: 80.0),
redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0),
redView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0),
redView.heightAnchor.constraint(equalToConstant: 80.0),
redView.widthAnchor.constraint(equalToConstant: 80.0)
])
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
let pan = UIPanGestureRecognizer(target: self, action: #selector(self.handlePanGesture(_:)))
yellowView.addGestureRecognizer(pan)
yellowViewOrigin = yellowView.frame.origin
view.bringSubview(toFront: yellowView)
}
@objc func handlePanGesture(_ sender: UIPanGestureRecognizer) {
let targetView = sender.view!
let translation = sender.translation(in: view)
switch sender.state {
case .began,.changed:
targetView.center = CGPoint(x: targetView.center.x + translation.x
,y: targetView.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: view)
case .ended:
if targetView.frame.intersects(redView.frame){
UIView.animate(withDuration: 0.3) {
targetView.alpha = 0.0
}
}
else{
UIView.animate(withDuration: 0.3) {
targetView.frame.origin = self.yellowViewOrigin
}
}
break
default:
break
}
}
}
PlaygroundPage.current.liveView = ViewController()
答案 1 :(得分:0)
我认为您需要在函数声明前添加@objc
标记,以便handleTap
对#selector
可见。
@objc func handleTap(sender: UITapGestureRecognizer) {
player.position = sender.location(in: view)
}
答案 2 :(得分:0)
func handleTap
类型调用 view
。
请尝试将其添加到SKView扩展程序中:
extension SKView {
func handleTap(sender: UITapGestureRecognizer) {
player.position = sender.location(in: view)
}
}