如何让 uiview 与控制器对话
我对 Objective-C 和 Cocoa 比较陌生......我已经尝试理解如何在 Cocoa/Cocoa Touch 中正确实现 MVC 模式很长时间了......我理解它背后的想法;从概念上讲,它是完全有意义的:模型保存数据,视图是用户看到并可以与之交互的内容,控制器充当两者之间的桥梁。视图无法与模型对话,模型也无法与视图对话。知道了。
对我来说没有意义的是如何有效地使用 MVC…如果用户只能与视图交互,并执行一些与之交互的操作(即对于 iPhone 应用程序,用户在 UIView 的子类中单击/拖动,触发“touchesBegan”和“touchesMoved”方法等),视图如何将这些事件传达给控制器?
我在网上查看了无数的示例和论坛,但尚未找到一种简化的通用方法来实现这一目标……我知道如何通过按钮、滑块和其他可以连接到插座的东西与控制器进行通信,但对于没有目标行动机制的事情,最好的方法是什么?
预先感谢您提供有关做什么或去哪里寻找的任何建议。
I'm relatively new to Objective-C and Cocoa... I've been trying to understand how to correctly implement the MVC pattern in Cocoa/Cocoa Touch for a long time now... I understand the idea behind it; it makes complete sense conceptually: a model holds the data, a view is what that the user sees and can interact with, and the controller acts as the bridge between the two. View can't talk to the model, model can't talk to the view. Got it.
What doesn't make sense to me is how to use MVC efficiently… if the user can only interact with the view, and does something to interact with it (i.e. for an iPhone app, the user clicks/drags within a subclass of UIView, triggering the "touchesBegan" and "touchesMoved" methods, etc.), how does the view communicate these events to the controller?
I've looked at countless examples and forums online, but have yet to find a simplified all-purpose way of achieving this… I know how to communicate with a controller through buttons, sliders, and other things that you can connect to an outlet, but for things that don't have a target-action mechanism, what's the best way to do it?
Thanks in advance for any suggestions regarding what to do, or where to look.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cocoa 中执行此操作的标准方法是委托模式(参见
UITableViewDelegate
)。您的视图类将声明委托协议,并且控制器将自身设置为视图的委托。然后,只要视图想要与控制器进行通信,它就会调用您定义的委托方法之一。另一种方法是自己为您的视图实现目标操作机制。如果您从
UIControl
子类化(只需调用sendActionsForControlEvents:
),那么您或多或少可以免费获得此功能,但是实现一个对任何自定义都以相同方式工作的系统非常容易(编辑:我想第三种方法是让控制器观察视图的属性(使用 KVO)。这不能很好地传达触摸事件,但如果您想通知控制器,这是一种可行的方法状态更改或类似的东西。)
The standard way in Cocoa to do this is the delegate pattern (cf.
UITableViewDelegate
). Your view class would declare a delegate protocol and the controller sets itself as the view's delegate. The view then calls one of the delegate methods you defined whenever it wants to communicate something to the controller.An alternative would be to implement the target-action mechanism for your view yourself. You get this more or less for free if you subclass from
UIControl
(just callsendActionsForControlEvents:
) but it is quite easy to implement a system that works the same way for any custom class.(Edit: I suppose a third way is to have the controller observe properties of the view (with KVO). This wouldn't work well to communicate touch events but it is a feasible way if you want to notify the controller about a state change or something like that.)