Search Your Question

How To declare custom tableview cell? What Is The Use Of dequeuereusablecellwithidentifier ?

Ans : 

Let's create custom cell :

1. Take viewcontroller or tableviewcontroller
2. In Tableview, put one uitableviewcell and change style to custom.
3. Give any string (i.e "newcell") to reuseidentifier of cell in attribute inspector.
4. Put labels, textfields, views in cell according to your need.
5. Add new file named as newCell.swift that inherit from UITableViewCell.
6. Select your cell and give class name newCell.
7. Now you can make outlet of that cell in newCell.swift.

Here magic will be created using dequeuereusablecellwithidentifier : 

The best part of using dequeueReusableCellWithIdentifier is that using this you can re-use your cells.

Imagine if your table has 1000 entries. Now, if for each entry a table cell would be created then for 1000 entries, 1000 tableview cells and memory allocation for 1000 tableview cells.

App will be slowed down or would crash if the entries goes beyond 1000.

When we use, dequeueReusableCellWithIdentifier, the tableView just creates exactly the number of cells based on your table height and cell height. Suppose, if it shows 4 cells in the tabelView and rest you can see by scrolling, then memory for only 4 cells would be allocated at any given point of time.

Now, when you will scroll the tableView, it will re-use the same cell but will change the cell content (data) based on your data source.

Hope this clears your doubt.

Code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:"newcell"];
    cell.textLabel.text = @"Test";
    return cell;

}

No comments:

Post a Comment

Thanks