简体   繁体   English

在UITableViewCell子类中处理UIButton触摸事件会违反MVC吗?

[英]Will handling UIButton touch event inside a UITableViewCell subclass violate MVC?

There is a UITableViewCell subclass with a UIButton inside. 有一个带有UIButtonUITableViewCell子类。 A web call should be made when the button is pressed. 按下按钮时应进行网络通话。

The question is whether I should set the action in the controller, or can the action be set within the UITableViewCell subclass? 问题是我应该在控制器中设置动作,还是可以在UITableViewCell子类中设置动作? Will the second option violate MVC pattern? 第二个选项会违反MVC模式吗?

The second option will certainly violate MVC pattern. 第二种选择肯定会违反MVC模式。 ViewController works like a glue between your models, views and contains all the business logic. ViewController就像模型,视图之间的胶水一样工作,并且包含所有业务逻辑。 ViewController should receive action then make your api call and put formatted data to your views. ViewController应该接收动作,然后进行api调用,并将格式化后的数据放入视图中。

Usually in my project I always try to move networking code into separated set of classes which can handle fetching data from API, transforming from JSON/XML to model objects and formatting them (string date object to NSDate object etc.). 通常在我的项目中,我总是尝试将网络代码移到一组单独的类中,这些类可以处理从API提取数据,从JSON / XML转换为模型对象并对其进行格式化(将字符串日期对象转换为NSDate对象等)。 Then I can call simple looking method in my ViewController and populate views/tableview cells. 然后,我可以在ViewController中调用外观简单的方法,并填充视图/ tableview单元格。

On the other hand, 另一方面,

If you have some time you can look at MVVM which is getting more popular. 如果您有时间,可以看一下越来越受欢迎的MVVM。 There are some links (start with sprynthesis which is AWESOME): 有一些链接(以sprynthesis开头,这是很棒的):

  1. www.sprynthesis.com www.sprynthesis.com
  2. objc.io objc.io
  3. cocoasamurai cocoasamurai
  4. raywenderlich raywenderlich

And some sample apps: 以及一些示例应用程序:

  1. C-41 C-41
  2. vinylogue vinylogue
  3. GroceryList 购物清单

That helped me to understand MVC more deeply thanks to comparision to MVVM. 通过与MVVM的比较,这有助于我更深入地了解MVC。

Don't be scared with usage of ReactiveCocoa, you can always adopt MVVM without it but it's worth to look at. 不要害怕使用ReactiveCocoa,如果没有它,您总是可以采用MVVM,但是值得一看。 (It has really steep learning curve and I still feel like an idiot) (它的学习曲线非常陡峭,我仍然觉得自己是个白痴)

Also there is a great article about design patterns with iOS implementation: 关于iOS实现的设计模式,还有一篇很棒的文章:

raywenderlich design patterns raywenderlich设计模式

好了,您可以从子类中将操作委派给控制器,这样就可以在控制器中对其进行处理,清除并且不会违反MVC。

I don't recommend to set the action within the UITableViewCell. 我不建议在UITableViewCell中设置操作。 What would you do if you need to wait for the answer and the cell needs to be recycle? 如果您需要等待答案并且需要回收电池,该怎么办? I will set the action in the controller. 我将在控制器中设置操作。 This controller should call another class in charge of performing the web call. 该控制器应呼叫另一个负责执行网络呼叫的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM