Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding a UITableView - how do I set the reuse identifier for the cells?

I have a UIViewController that at some point grows a UITableView, and when it does I simply init the TableView instance variable and add it to the view, but I'm not sure how to handle the dequeueing of cells to add to the view; I need a reuse identifier, but I'm not sure how to set it.

What do I do within this method?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"wot";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    return cell;
}
like image 286
Doug Smith Avatar asked Apr 02 '13 19:04

Doug Smith


People also ask

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

What is the reuse identifier in table view used for?

The reuse identifier is associated with a UITableViewCell object that the table-view's delegate creates with the intent to reuse it as the basis (for performance reasons) for multiple rows of a table view. It is assigned to the cell object in initWithFrame:reuseIdentifier: and cannot be changed thereafter.

How do I populate UITableView?

There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.

Is it possible to add UITableView within a UITableViewCell?

Implementation of adding a table view inside the cell of UItableview aka, Nested Table View. Used the Power of Autosizing table view and delegate to achieve the expansion and collapse of the cell height.


1 Answers

Use the method initWithStyle:reuseIdentifier

  1. check if cell exists
  2. If it doesn't, then you need to initialize it.

code

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath*)indexPath 
{
    static NSString *cellIdentifier = @"wot";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle: someStyle reuseIdentifier: cellIdentifier];

    return cell;
}
like image 81
MJN Avatar answered Sep 21 '22 02:09

MJN