agf119105
agf119105

Reputation: 1810

How can I find button tag after implementing gesture recogniser in swift?

I want an action to be done once when someone swipes within a button.

My current code is as follows:

    let recogniser = UISwipeGestureRecognizer(target: self, action: "didTapButton2:")
    recogniser.direction = .Up
    button.addGestureRecognizer(recogniser)

    func didTapButton2(sender: UIGestureRecognizer!) {

    //Here I want to be able to recognise which button this was sent from (they are all tagged)
    let button = sender. as UIButton //Gives an error

I need to use gesture recognisers as opposed to UIControlEvents as I need the event to only fire once. Using this makes the event fire loads of times - just need it to go once:

    button.addTarget(self, action: "didTapButton2:", forControlEvents: .TouchDragInside)

Does anyone have a solution? Thanks

Upvotes: 2

Views: 3601

Answers (1)

vacawama
vacawama

Reputation: 154583

A UIGestureRecognizer has a property called view which is the view that it is attached to. View is declared as an optional, so you need to unwrap it:

if let button = sender.view as? UIButton {
    // use button
    if button.tag == 10 {
        // handle button tagged with 10
    }
}

Upvotes: 6

Related Questions