长按通过按钮识别手势 - Swift 3



我是 Swift 的新手,我正在尝试制作从长按按钮开始的计时器(在标签中(。同时我想在长按按钮时更改长按按钮图像。我离开按钮,我希望按钮恢复原状。

可能出了什么问题?

@IBOutlet weak var myBtn: UIButton!
func initGesture()
{
{   let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
myBtn.addGestureRecognizer(longGesture)
}
}
func TimerAction()
{
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(longTap), userInfo: nil, repeats: false)
myBtn.setImage(UIImage(named: "xxx.png"), for: .normal)

}
@IBOutlet weak var lbl: UILabel!
func start()
{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController2.updateTime as (ViewController2) -> () -> ())), userInfo: nil, repeats: true)
}
func updateTimer () {
count += 1
let hours = Int(count) / 3600
let minutes = Int(count) / 60 % 60
let seconds = Int(count) % 60
label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds)
}
func reset()
{
timer.invalidate()
count = 0
label.text = "00:00:00"
}

你可以得到 TouchUpInside 和 TouchUpOutside,按钮的 TouchDown 操作不使用手势。

class ViewController: UIViewController {
@IBOutlet weak var lbl: UILabel!
@IBOutlet weak var myBtn: UIButton!
var timer: NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
myBtn.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown)
myBtn.addTarget(self, action: "buttonUp:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
}
func buttonDown(sender: AnyObject) {
singleFire()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "rapidFire", userInfo: nil, repeats: true)
}
func buttonUp(sender: AnyObject) {
timer.invalidate()
count = 0
label.text = "00:00:00"
}
func singleFire() {
myBtn.setImage(UIImage(named: "xxx.png"), for: .normal)
}
func rapidFire() {
count += 1
let hours = Int(count) / 3600
let minutes = Int(count) / 60 % 60
let seconds = Int(count) % 60
label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds)
}
}

您应该实现按钮事件,而不是在此处使用手势识别器。我谈论的按钮事件是TouchDown和TouchUpInside。TouchDown 会告诉您何时按下按钮,touchupinside 会告诉您用户何时将手指从按钮上抬起。

因此,您将更改按钮图像并在触地事件时启动计时器。然后,您将恢复到内部事件。

https://developer.apple.com/documentation/uikit/uicontrolevents

试试这个,

首先根据按钮的状态设置按钮的图像。

self.arrowIcon.setImage(UIImage(named: "normalImage.png"), for: .normal)
self.arrowIcon.setImage(UIImage(named: "pressedImage.png"), for: .highlighted)

最新更新