当您按住按钮时,您希望快速重复射击。
Your buttonDown
and buttonUp
方法需要在顶层定义,而不是在另一个函数内部定义。出于演示目的,放弃接线会更清楚@IBAction
s 从故事板,只需设置按钮viewDidLoad
:
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
var timer: Timer?
var speedAmmo = 20
@objc func buttonDown(_ sender: UIButton) {
singleFire()
timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(rapidFire), userInfo: nil, repeats: true)
}
@objc func buttonUp(_ sender: UIButton) {
timer?.invalidate()
}
func singleFire() {
print("bang!")
}
@objc func rapidFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer?.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// These could be added in the Storyboard instead if you mark
// buttonDown and buttonUp with @IBAction
button.addTarget(self, action: #selector(buttonDown), for: .touchDown)
button.addTarget(self, action: #selector(buttonUp), for: [.touchUpInside, .touchUpOutside])
}
}
另外,我也改变了.touchUpOutside
to [.touchUpInside, .touchUpOutside]
(捕获两个触摸事件)并调用singleFire
在最初的buttonDown
用于单火。通过这些更改,按下按钮会立即触发,然后触发每个0.3
只要按住按钮,就会持续几秒钟。
The button can be wired up in the Storyboard instead of setting it up in viewDidLoad
. In this case, add @IBAction
to buttonDown
and buttonUp
. Then Control-click on your button in the Storyboard and drag from the circle next to Touch Down to func buttonDown
, and drag from the circles next to Touch Up Inside and Touch Up Outside to func buttonUp
.