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)
}
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)
}