0

I have a lot of UIButtons without any acion. I want call some action in tap handler function. I create single tap with UITapGestureRecognizer. When I tap not on my UIButton, single tap handler work. When I tap on my UIButton, I see animation of pressing this button, but single tap handler doesn't work. Also I create double tap, and it works fine.

Question №1
What I can do with single tap? Handler should work, when I tap on my UIButton.

Question №2
How I can get UIButton in tap handler? I need get text label from this button.

Part of my code:

override func viewDidLoad() {
    ...

    let singleTap = UITapGestureRecognizer(target: self, action: "singleTap:")
    singleTap.numberOfTapsRequired = 1
    singleTap.numberOfTouchesRequired = 1
    view.addGestureRecognizer(singleTap)

    let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
    doubleTap.numberOfTapsRequired = 2
    doubleTap.numberOfTouchesRequired = 1
    view.addGestureRecognizer(doubleTap)
    singleTap.requireGestureRecognizerToFail(doubleTap)

    ...
}

func doubleTap(sender: UIGestureRecognizer) {
    if sender.state == .Ended {
        print("doubleTap")
    }
}

func singleTap(sender: UIGestureRecognizer) {
    if sender.state == .Ended {
        print("singleTap")
    }
}

func addButton(time:String, x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, tag: Int) -> UIButton {
    let button = UIButton(type: UIButtonType.System) as UIButton
    button.frame = CGRectMake(x, y, width, height)
    button.setTitle(time, forState: UIControlState.Normal)
    button.tag = tag
    self.scrollView.addSubview(button)
    return button
}
iserdmi
  • 75
  • 1
  • 11
  • 1
    why don't you use IBAction for button? – Bista Jan 12 '16 at 06:06
  • `view.addGestureRecognizer(singleTap)` suggest that single tap is applied on view not on `button` – Bista Jan 12 '16 at 06:11
  • Disable user interaction for each UIButtons or add handlers for all buttons. – Aruna Mudnoor Jan 12 '16 at 06:19
  • @IOSDeveloper - right also add `button.enabled=NO`, first define `button` globally. though this might be helpful : http://stackoverflow.com/questions/4825199/gesture-recognizer-and-button-actions – Bista Jan 12 '16 at 06:19

1 Answers1

0

If you want to add TapGesture into Button then do it like this way:

let singleTap = UITapGestureRecognizer(target: self, action: "singleTap:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
yourButton.addGestureRecognizer(singleTap)
riddhi
  • 316
  • 2
  • 16
  • Thanks a lot. I have thought that UITapGestureRecognizer works only on views. To get text lable I use this part of code in handler: `(sender.view as! UIButton).titleLabel!.text!` – iserdmi Jan 12 '16 at 06:34