如何区分哪些代码放在 View 中,哪些代码放在 ViewController 中? [英] How to differentiate what code put in View and what in ViewController?

查看:42
本文介绍了如何区分哪些代码放在 View 中,哪些代码放在 ViewController 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 UIView 子类中有相当大的目标操作实现,所以我的视图文件(来自 MVC)似乎有一些代码,这与安排 UIView 屏幕上的对象.这是遵循MVC模式的正确方法吗?如果没有,正确的处理方法是什么?

I have pretty big implementation of target actions in my UIView subclass, so my View file (from MVC) seems to have some code, which is not really connected to arranging UIView objects on a screen. Is it a right way to follow MVC pattern? If not, what is the right way to deal with it?

推荐答案

这完全取决于这些目标操作正在做什么.

It depends entirely what these target actions are doing.

  • 如果它们与视图相关(例如拉出菜单、向后滑动、移动子视图等的控件),那么将所有这些都封装在视图类中可能是合理的.

  • If they’re view-related (e.g. controls to pull out menu, slide it back, move subviews, etc.) then encapsulating all of this within the view class might be reasonable.

但是,如果这些操作包括业务逻辑、网络请求、本地数据存储的操作等,那么将它们放在 UIView 子类下很可能与你应该做什么.

If, however, these actions include business logic, network requests, manipulation of local data stores, etc., then squirreling them under UIView subclasses is likely to be the exact opposite direction of what you should do.

就构建应用程序的模式而言,有许多替代方案,包括:

In terms of patterns for structuring your app, there are a host of alternatives, including:

  • 参见 Dave Delong 的 更好的 MVC,了解拥抱 MVC 但采用技术来保持它们的观点小而易于管理.

  • See Dave Delong’s A Better MVC for a perspective of embracing MVC but employing techniques to keep them small and manageable.

查看 Medium iOS 架构模式 查看其他方法,包括 MVP、MVVM、Viper 等.

See Medium’s iOS Architecture Patterns for a review of other approaches ranging from MVP, MVVM, Viper, etc.

请参阅 Krzysztof Zabłocki 的 iOS 应用程序架构,了解有关该主题的另一个很好的讨论.

See Krzysztof Zabłocki’s iOS Application Architecture for another good discussion on the topic.

我不会把我的拇指放在规模上并提倡一种特定的模式而不是另一种(这是一个意见问题,因此,对于 Stack Overflow 来说是题外话),但是当你经历所有以上,一致的主题是职责分离,使我们的代码更容易推理,并提高可测试性.

I’m not going to put my thumb on the scale and advocate one particular pattern over another (this is a matter of opinion, and, as such, is off-topic for Stack Overflow), but as you go through all of the above, the consistent theme is a separation of responsibilities, making it easier to reason about our code, and improved testability.

最重要的是,将特定于视图的代码移动到您的 UIView 子类中很好,但将业务/应用程序逻辑放入视图中是一种反模式.

Bottom line, moving view-specific code into your UIView subclasses is fine, but putting business/app logic into views is an anti-pattern.

这篇关于如何区分哪些代码放在 View 中,哪些代码放在 ViewController 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆