提问人:Sham Dhiman 提问时间:9/27/2023 最后编辑:Witek BobrowskiSham Dhiman 更新时间:9/27/2023 访问量:82
点击手势在 Circle Swift 上不起作用
Tap Gesture not working on the Circle Swift
问:
我正在创建一个单页游戏,您可以在其中选择一个圆圈,然后分数级别会增加。我几乎完成了它,但我的点击手势在圆圈上不起作用。我已经尝试了下面的代码,但它不起作用。请检查下面的代码。
import UIKit
import AVFoundation
class Demogame: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
var score = 0
var isGameOver = false
override func viewDidLoad() {
super.viewDidLoad()
startGame()
}
func startGame() {
score = 0
scoreLabel.text = "Score: \(score)"
isGameOver = false
// Create a timer to spawn circles
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
if !self.isGameOver {
self.spawnCircle()
} else {
timer.invalidate()
}
}
}
func spawnCircle() {
let circleSize = CGSize(width: 50, height: 50)
let circleView = UIView(frame: CGRect(origin: CGPoint(x: CGFloat.random(in: 50...view.frame.width - circleSize.width - 50),
y: CGFloat.random(in: 100...view.frame.height - circleSize.height - 50)),
size: circleSize))
circleView.backgroundColor = UIColor.random()
circleView.layer.cornerRadius = circleSize.width / 2
view.addSubview(circleView)
// Add a tap gesture recognizer to each circle
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
circleView.addGestureRecognizer(tapGesture)
// Animate the circle's appearance and disappearance
UIView.animate(withDuration: 3.0, animations: {
circleView.alpha = 0.0
}) { (completed) in
if completed {
circleView.removeFromSuperview()
}
}
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
if isGameOver {
return
}
if let tappedView = sender.view {
tappedView.removeFromSuperview()
score += 1
scoreLabel.text = "Score: \(score)"
}
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: CGFloat.random(in: 0.0...1.0),
green: CGFloat.random(in: 0.0...1.0),
blue: CGFloat.random(in: 0.0...1.0),
alpha: 1.0
)
}
}
问题:如何在圆圈上点击手势并提高分数级别?
有人可以向我解释一下如何做到这一点吗,我已经尝试过上面的代码,但还没有结果。如果我做错了,请纠正我。
任何帮助将不胜感激
答:
3赞
DonMag
9/27/2023
#1
视图 - 按钮、标签、图像视图、普通视图等 - 当小于.alpha
0.01
可能不明显的是,当我们像这样编写动画块时:
UIView.animate(withDuration: 3.0, animations: {
circleView.alpha = 0.0
})
UIKit 会立即评估块内的指令,然后计算动画视觉效果。
因此,一旦动画开始,UIKit 就会认为它有一个 -- 所以,没有触摸事件/点击手势。circleView
.alpha
0.0
另一个问题是,默认情况下,您无法在动画期间与 UI 元素进行交互。
您可以通过将动画选项设置为 来解决此问题。.allowUserInteraction
如果将动画块更改为:
UIView.animate(withDuration: 3.0, delay: 0.0, options: .allowUserInteraction, animations: {
circleView.alpha = 0.05
}, completion: { b in
if b {
circleView.removeFromSuperview()
}
})
您现在应该能够点击圆圈了。
1赞
Mykyta iOS
9/27/2023
#2
将动画块重写为以下内容:
UIView.animate(withDuration: 3.0,
delay: 0.0,
options: .allowUserInteraction
animations: { circleView.backgroundColor = .clear },
completion: { completed in
if completed {
circleView.removeFromSuperview()
}
})
- 将视图 Alpha 设置为零会禁用命中测试,因此请改用透明颜色。
- 将“允许用户交互”选项添加到动画中。
评论
.allowUserInteraction