简体   繁体   中英

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

There is a UITableViewCell subclass with a UIButton inside. 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? Will the second option violate MVC pattern?

The second option will certainly violate MVC pattern. ViewController works like a glue between your models, views and contains all the business logic. ViewController should receive action then make your api call and put formatted data to your views.

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.). Then I can call simple looking method in my ViewController and populate views/tableview cells.

On the other hand,

If you have some time you can look at MVVM which is getting more popular. There are some links (start with sprynthesis which is AWESOME):

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

And some sample apps:

  1. C-41
  2. vinylogue
  3. GroceryList

That helped me to understand MVC more deeply thanks to comparision to MVVM.

Don't be scared with usage of ReactiveCocoa, you can always adopt MVVM without it but it's worth to look at. (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:

raywenderlich design patterns

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

I don't recommend to set the action within the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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