What is the proper way to handle the actions (events) of the UITableView cell routines?

I have UITableView

with custom cells. Each cell has a rather complex layout and many child views, all of which have events: UIImageView

with gesture recognizer, several UIButtons

with some actions, two UILabel

with gesture recognizers. So I'm wondering if there are some neat ways to handle the targeted action for them? Now I see three ways:

  • Manage actions with blocks ( BlocksKit

    to the rescue) right incellForRowAtIndexPath:

  • Create your own class CellEventHandler

    , pass it all the required dependencies (controller navigation controller

    , dataset, etc.) and place all the neighbor action selectors.
  • Enter all selectors in TableViewController (default)

But I am not satisfied with all these ways. Can someone describe some elegant way that will help make the controller slim and also easy to maintain. I'm sure there must be some pattern for this workflow.

+3


source to share


3 answers


Use delegation. When creating a cell, set the delegate attribute to some instance that matches your delegation protocol. When actions are initiated, simply delegate the behavior to the delegate.



This way you get a well-defined delegation protocol and functionality encapsulated in this class. It is up to you if there will be a delegate for example. TableViewController or custom class.

+4


source


I think the most efficient way to handle complex cells is to subclass UITableViewCell and have all events handled directly in the subclass. You can directly create IBOutlets and Idle.



In C, viewForRowAtIndexPath

you can simply call a custom function initWithObject

that you can declare in the header of your class, so even the initial cell setup goes outside the viewController, making customization much easier.

+1


source


The views and actions should be in the view of the MVC pattern, which is a custom cell in your case. You must write one method for gestureRecognizer (tapGestureRecognizer added to your cell) in your custom cell class. The method will identify the type of object that invokes it through introspection, i.e. isKindOfClass UIButton / Label / ImageView. Each object will additionally identify it with its own tag, for example if the gestureRecognizer says it is a label that calls this method, but against label1 or label2 you can now compare your tag to detect it.

0


source







All Articles