Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a UITapGestureRecognizers Target

I am trying to create a basic view, whose backgroundColor is toggled between two colors each time it is tapped. To achieve this I created a function that takes as arguments the view to be changed and the two colors to toggle between.

For this to work I need to pass the UIView that it should then change. But UIViews can't natively recognize touches so I "linked" (I am unsure I understood this right) a UITapGestureRecognizer to it that triggers an action in my ViewController.

Now I need to get the UITapGestures linked UIView so I can change it.

I realize I could simple enter the corresponding UIView into the action, but I want to make this function as flexible as possible (just trying to start out with the right etiquette).

Here is my imcomplete function:

@IBAction func colorViewTapped(_ sender: Any) {
    print("tap")
    //Heres the problem: I get an "Cannot convert value of type 'Any' to expected argument type 'UIView'
    toggleViewBackgroundColor(view: sender, color1: UIColor.blue, color2: UIColor.brown)
}
like image 920
Marmelador Avatar asked Jun 19 '26 05:06

Marmelador


1 Answers

Change your action method argument type to UITapGestureRecognizer from Any and then use view property of UIGestureRecognizer to get the reference of tapped view.

@IBAction func colorViewTapped(_ sender: UITapGestureRecognizer) {
    print("tap")
    toggleViewBackgroundColor(view: sender.view!, color1: UIColor.blue, color2: UIColor.brown)
}
like image 134
Nirav D Avatar answered Jun 21 '26 17:06

Nirav D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!