[英]How to get the button text if a long press gesture on the button is triggered in swift?
[英]Long Press Recognize Gesture via Button - 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会告诉您何时用户将手指从按钮上抬起。
因此,您将更改按钮图像并在触地事件上启动计时器。 然后,您将在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.