0

I got a card that is draw by a custom view. I want to add a swipe gesture to every card for flip and being chosen. Since every card view needs the gesture, I choose to add the gesture in the method initWithFrame: of the view. However,I want to leave it to my controller to handle this gesture when it was recognized because choosing the card is a method in my controller. Here is my code:

[self addGestureRecognizer:[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)]];

Actually I need the target to be my controller, I want to call a method named swipe in my controller. the target self only leave the handling of gesture to view itself.

Maybe I can't simply get my controller to replace the target.Can anyone tell my the correct way to solve this problem?

HRLTY
  • 74
  • 10

2 Answers2

2

Your view should not know what its controller is. (This would increase coupling and decrease cohesion, which is bad.)

A common solution to this problem is for your view to declare a delegate protocol. Your view controller can set itself as the view's delegate. Your view's swipe: method would then call the delegate method.

For example code, see this question.

Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • +1 from me. A signature like -(void) cardDidSwipe:(CardView *) card; is more helpful, this way the card view can pass itself to the delegate (assuming there are many card). – Kaan Dedeoglu Sep 19 '14 at 15:24
1

Can anyone tell my the correct way to solve this problem?

If the gesture's action in in the view controller, perhaps you should let the view controller add the gesture to the view. The view controller is in a good position to do that, having references to both the view and to itself. There are a number of places where you could do the work -- -viewDidLoad for example.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • This solution will work, although if the card view is used in multiple controllers you'll end up with duplicate gesture recognizer code in each controller. – Aaron Brager Sep 19 '14 at 15:59