我有一个UIViewController,其视图有一个自定义子视图。当发生子视图触摸事件时通知视图控制器
此自定义子视图需要跟踪触摸事件并报告滑动手势。
目前我把touchesBegan,touchesMoved,touchesEnded和touchesCancelled在子视图类中。通过一些额外的逻辑,我可以轻扫手势并调用我的handleRightSwipe和handleLeftSwipe方法。所以现在当我在子视图中滑动时,它会调用其本地刷卡处理方法。这一切工作正常。
但我真正需要的是handleRightSwipe和handleLeftSwipe方法在视图控制器中。我可以将它们留在子视图类中,但是我必须引入所有的逻辑和数据,并且这种打破了MVC的想法。
所以我的问题是有一个干净的方式来处理这个问题?基本上我想保留我的触摸事件方法在子视图中,以便它们只触发特定的视图。但是我也希望当这些触摸事件(或者在这种情况下是轻扫手势)发生时通知视图控制器。
任何想法?
谢谢。
UPDATE:
使用Henrik的建议,下面是我做了什么(以节省您的读数)的快速样品:
设置我的视图控制器作为通知的观察者(早期) 。
// NOTIFICATION_LEFT_SWIPE is defined as some unique string elsewhere.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
// Note that imageView is the instance of my subview that is calling the notification.
// You can set this to nil if you don't want it to be specific.
[nc addObserver:self selector:@selector(handleLeftSwipe) name:@NOTIFICATION_LEFT_SWIPE object:imageView];
然后我执行handleLeftSwipe方法。这将在收到通知时被调用。
现在在我的子视图我送收到轻扫手势时通知:
// Note that NOTIFICATION_LEFT_SWIPE is the same one used in the view controller
// I put this in a global header I use. This is how you keep track of notifications.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@NOTIFICATION_LEFT_SWIPE object:self];
同样地,对于右轻扫。
啊谢谢你先生!这工作完美。我甚至没有听说过通知中心,但它确实是我所需要的。 – nebs 2010-06-16 20:16:07