Aeveus
Aeveus

Reputation: 5382

Where to add event handlers

It appears there are multiple places to add event handlers for targets. Currently I have a slider in a UITableViewCell with multiple methods hooked up to control events: UIControlEventValueChanged, UIControlEventTouchUpInside and UIControlEventTouchUpOutside.

These are added currently added within the layoutSubviews method, but I'm not sure if that is the right place. I tried moving them to the UITableViewController (as in I add them in the tableView: cellForRowAtIndexPath: method), but now I'm not sure what the correct place is to add these things.

Should I keep them in the layoutSubviews (which is called repeatedly over time, because of scrolling, not sure what this does to the event handlers, do they get added multiple times?), move it to the initWithStyle (also not sure about this one, I tried an NSLog in this method, but it wasn't called even once), or put it in the UITableViewController?

Upvotes: 2

Views: 92

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

The layoutSubviews method is definitely not the right place: it is there for controlling the layout, not to hook up event handlers - not to mention a possibility of hooking up the same handler multiple times!

The right place to add events to standard cells is the tableView: cellForRowAtIndexPath: method. For custom cells drawn using Interface Builder you should be able to connect the events visually.

Upvotes: 1

Wain
Wain

Reputation: 119031

You should add them when the slider is created. If the slider is created in an XIB then you should really add the connection there too, otherwise you would add it in viewDidLoad or, depending on your construction, awakeFromNib. If the slider is created in code then add them immediately after the creation.

Upvotes: 1

Related Questions