【发布时间】:2010-06-16 19:45:06
【问题描述】:
我有一个 UIViewController,它的视图有一个自定义子视图。
此自定义子视图需要跟踪触摸事件并报告滑动手势。
目前我将 touchesBegan、touchesMoved、touchesEnded 和 touchesCancelled 放在子视图类中。通过一些额外的逻辑,我可以获得滑动手势并调用我的 handleRightSwipe 和 handleLeftSwipe 方法。所以现在当我在子视图中滑动时,它会调用它的本地滑动处理方法。这一切都很好。
但我真正需要的是将 handleRightSwipe 和 handleLeftSwipe 方法放在视图控制器中。我可以将它们留在子视图类中,但我必须同时引入所有逻辑和数据,这打破了 MVC 的想法。
所以我的问题是有没有一种干净的方法来处理这个问题?本质上,我想将我的触摸事件方法保留在子视图中,以便它们仅触发该特定视图。但我也希望在这些触摸事件(或本例中的滑动手势)发生时通知视图控制器。
有什么想法吗?
谢谢。
更新:
使用 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];
同样适用于向右滑动。
【问题讨论】:
标签: iphone uiviewcontroller uiresponder