Use a different init method for dequeueReusableCellWithIdentifier

I want to use my own UITableViewCell class, so in the corresponding UITableViewController I write

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentitfier, forIndexPath: indexPath) as MyTableViewCell //cellIdentifier is initialized return cell } 

However, I want to initialize my cell, since I need to pass arguments when it is created. Apple docs say that dequeueReusableCellWithIdentifier calls (if the cell needs to be initialized) initWithStyle:reuseIdentifier .

If there is a cell for reuse, the method calls prepareForReuse .

In any case, I want to pass arguments to my cell before executing other methods (i.e. during initialization and in prepareForReuse, respectively).

What is a suitable way to do this, and is there a way to use other initializers, as defined in a class derived from UITableViewCell (MyTableViewCell)?

+6
source share
1 answer

If you want to have your own init method, you must: (a) make sure that you do not have a cell prototype (for example, if you do this, it will call the initializer itself); and (b) your cellForRowAtIndexPath properly handles when a reusable cell is not found, and therefore you must create your instance (with any parameters you want.

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as MyTableViewCell? if cell == nil { cell = MyTableViewCell(param1: "foo", param2: "bar", reuseIdentifier: cellIdentifier) // configure new cell here } else { // reconfigure reused cell here } return cell! } 

Personally, however, I would not be inclined to follow this route. I would prefer to use cell prototypes and standard initialization procedures, but then, if necessary, just override the properties (or call some configuration function), for example:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as MyTableViewCell cell.property1 = "Foo" cell.property2 = "Bar" return cell } 

Thus, I can enjoy the prototype of the cell, automatically create a class of cell objects, display IBOutlets and IBActions, etc., but perform any special configuration that I need here in cellForRowAtIndexPath .

0
source

Source: https://habr.com/ru/post/977082/


All Articles