我有一个带6个按钮的屏幕。所有按钮都连接到一个IBAction
。它们被标记,我使用switch语句来确定哪个被点击。
如何为每个按钮添加长按和手势?例如,当我点击按钮1时,它知道它是一个长手势还是一个轻敲手势?
因此,如果我按下按钮会做出不同的事情,那么当我长按时。
感谢。
@IBAction func playPauseAudioButton(sender: UIButton) {
switch sender.tag {
case 1:
//Tap Gesture
//Long Gesture
//I need this for every button
print("1")
case 2:
print("2")
case 3:
print("3")
case 4:
case 5:
print("5")
case 6:
print("6")
default:
print("Default")
}
}
答案 0 :(得分:5)
这样做
@IBAction func playPauseAudioButton(sender: AnyObject) {
let tapGesture = UITapGestureRecognizer(target: self, action: "normalTap:")
let longGesture = UILongPressGestureRecognizer(target: self, action: "longTap:")
tapGesture.numberOfTapsRequired = 1
sender.addGestureRecognizer(tapGesture)
sender.addGestureRecognizer(longGesture)
}
func normalTap(sender : UIGestureRecognizer) {
let recognizer: UIGestureRecognizer = sender
let tag: Int = recognizer.view!.tag
switch tag {
case 1:
// Do some action for button 1
print("1")
case 2:
print("2")
case 3:
print("3")
case 4:
print("4")
case 5:
print("5")
case 6:
print("6")
default:
print("Default")
}
}
func longTap(sender : UIGestureRecognizer) {
let recognizer: UIGestureRecognizer = sender
let tag: Int = recognizer.view!.tag
if sender.state == .Ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
}
else if sender.state == .Began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
switch tag {
case 1:
// Do some action for button 1
print("1")
case 2:
print("2")
case 3:
print("3")
case 4:
print("4")
case 5:
print("5")
case 6:
print("6")
default:
print("Default")
}
}
答案 1 :(得分:0)
定义两个IBActions并为每个IBActions设置一个手势识别器。这样,您可以为每个手势执行两个不同的操作。
您可以在界面构建器中将每个手势识别器设置为不同的IBAction。
@IBAction func tapped(sender: UITapGestureRecognizer)
{
println("tapped")
//Your animation code.
}
@IBAction func longPressed(sender: UILongPressGestureRecognizer)
{
println("longpressed")
//Different code
}
通过没有界面构建器的代码
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
self.view.addGestureRecognizer(tapGestureRecognizer)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.view.addGestureRecognizer(longPressRecognizer)
func tapped(sender: UITapGestureRecognizer)
{
println("tapped")
}
func longPressed(sender: UILongPressGestureRecognizer)
{
println("longpressed")
}
希望这会对你有所帮助。