单按和长按事件的UIButton迅速

我想触发button clickbutton long click 。 我在界面生成器中添加了一个UIbutton 。 我如何触发两个行动使用IBAction有人可以告诉我如何存档这个?

这是我用来点击button的代码

@IBAction func buttonPressed (sender: UIButton) { .... }

我可以使用这种方法,或者我必须使用另一种方法进行长时间的点击吗?

如果你想单击你的任何动作,并长按你可以添加手势到button这种方式:

 @IBOutlet weak var btn: UIButton! override func viewDidLoad() { let tapGesture = UITapGestureRecognizer(target: self, action: "Tap") //Tap function will call when user tap on button let longGesture = UILongPressGestureRecognizer(target: self, action: "Long") //Long function will call when user long press on button. tapGesture.numberOfTapsRequired = 1 btn.addGestureRecognizer(tapGesture) btn.addGestureRecognizer(longGesture) } func Tap() { println("Tap happend") } func Long() { println("Long press") } 

这样你可以添加多个单一button的方法,你只需要该button的Outlet。

为什么不创build一个自定义的UIButton类,创build一个协议,让button发送信息给代表。 像这样的东西:

  //create your button using a factory (it'll be easier of course) //For example you could have a variable in the custom class to have a unique identifier, or just use the tag property) func createButtonWithInfo(buttonInfo: [String: Any]) -> CustomUIButton { let button = UIButton(type: .custom) button.tapDelegate = self /* Add gesture recognizers to the button as well as any other info in the buttonInfo */ return button } func buttonDelegateReceivedTapGestureRecognizerFrom(button: CustomUIButton){ //Whatever you want to do }