简体   繁体   中英

Single tap, created by UITapGestureRecognizer, doesn't work on UIButton

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
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM