我的UI上有多个按钮,我想根据不同的点击类型执行不同的功能,
对我来说这样做很简单,IBAction连接了所有四个按钮,但是对于其他类型的点击我被卡住了,
我知道我需要使用点击手势识别器,但我无法将其设置为多个UIButtons,
这是我想做的事情的例子
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func ButtonSingleTap(sender:UIButton!) {
let ButtonNumber: String = String(sender.tag)
Label.text = "Button " + ButtonNumber + " is Single Tapped"
}
func ButtonDoubleTap(sender:UIButton!) {
let ButtonNumber: String = String(sender.tag)
Label.text = "Button " + ButtonNumber + " is Double Tapped"
}
func ButtonLongTap(sender:UIButton!) {
let ButtonNumber: String = String(sender.tag)
Label.text = "Button " + ButtonNumber + " is Long Pressed"
}
}
答案 0 :(得分:4)
您不能将UIGestureRecognizer
的一个实例用于多个按钮。每个按钮都需要自己的一组手势识别器。
以下是向您展示如何操作的示例:
for button in [button1, button2, button3, button4] {
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("didLongPress:"))
let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: Selector("didDoubleTap:"))
doubleTapRecognizer.numberOfTapsRequired = 2
button.addGestureRecognizer(longPressRecognizer)
button.addGestureRecognizer(doubleTapRecognizer)
}
func didLongPress(recognizer: UILongPressGestureRecognizer) {
guard let button = recognizer.view as? UIButton else { return }
switch recognizer.state {
case .Began:
print("long press began button \(button.tag)")
case .Ended:
print("long press ended button \(button.tag)")
default:
break
}
}
func didDoubleTap(recognizer: UITapGestureRecognizer) {
guard let button = recognizer.view as? UIButton else { return }
print("double tap button \(button.tag)")
}
要实现此目的,您必须为按钮添加Outlets(button1
,button2
,button3
,button4
)。