由UITapGestureRecognizer创建的单击不适用于UIButton

时间:2016-01-12 06:01:03

标签: ios swift uibutton uigesturerecognizer gesture

我有很多UIButtons没有任何acion。我想在tap处理函数中调用一些动作。我使用UITapGestureRecognizer创建单击。当我在我的UIButton上点击 not 时,单击处理程序工作。当我点击我的UIButton时,我看到按下此按钮的动画,但单击处理程序不起作用。我也创建了双击,它工作正常。

问题№1
单击可以做什么?当我点击我的UIButton时,处理程序应该可以工作。

问题№2
我如何在tap处理程序中获取UIButton?我需要从这个按钮获取文本标签。

我的部分代码:

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
}

1 个答案:

答案 0 :(得分:0)

如果你想将TapGesture添加到Button中,那就这样做:

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