MrASquare
MrASquare

Reputation: 139

Button as Parameter in Swipe Gesture Action in Swift

I just started working with swipe gestures in Swift. I am trying to use them with buttons: an action is supposed to be performed when the user swipes across a button.

In my viewDidLoad() of a ViewController-class I got:

let leftSwipeButton = UISwipeGestureRecognizer(target: self, action: "leftSwipeButtonAction")
leftSwipeButton.direction = .Left

myFirstButton.addGestureRecognizer(leftSwipeButton)
mySecondButton.addGestureRecognizer(leftSwipeButton)
myThirdButton.addGestureRecognizer(leftSwipeButton)

myFirstButton, mySecondButton and myThirdButton are buttons (UIButton).

And on the same level as viewDidLoad() I defined the action:

    func leftSwipeButtonAction() {
    // here the .backgroundColor of the button that was swiped is supposed to be set to UIColor.yellowColor()
}

As I want to use leftSwipeButtonAction() with the same functionality for multiple buttons I do not want to write a function for every single button, but rather pass the UIButton that was swiped as a parameter to leftSwipeButtonAction(). Is there a way to do this?

Upvotes: 1

Views: 1901

Answers (1)

Steve
Steve

Reputation: 959

You can send only the UITapGestureRecognizer itself as parameter on selector. You have to put : after selector name

let leftSwipeButton = UISwipeGestureRecognizer(target: self, action: "leftSwipeButtonAction:")

func leftSwipeButtonAction(recognizer:UITapGestureRecognizer) {
    //You could access to sender view
    print(recognizer.view?)
}

Upvotes: 2

Related Questions