Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable UITableView's prototype cell

I want to create a prototype cell which can be used in different table view via the storyboard.. What is the right way to do this? Any pointers appreciated.

like image 859
user3431473 Avatar asked Apr 06 '14 19:04

user3431473


1 Answers

I don't think you can create a prototype cell and share it between tables in a storyboard, but you can create a prototype cell in a nib and then load that in the ViewDidLoad method and then use that in your table view. It is really quite simple, here is how...

A. add the nib file:
1. Select New File... 2. Select IOS -> User Interface
3. Select "Empty" -> this will add a new file .xib file to your project
4. Drag a UITableViewCell from the object browser into your xib file and customize to your liking
5. Use the Utilities pane to change properties -> editing a nib is very similar to editing a storyboard.
6. Make sure you name your cell - I chose the name cellFromNib, but you will probably want something else.

B. Load the UITableViewCell in each table's viewDidLoad method:

- (void)viewDidLoad
{
   // load the cell in the nib - the nib can only contain this one UITableViewCell
   [self.tableView
         registerNib:[UINib nibWithNibName:[self @"nibFileNameWithoutExtension"]
                                    bundle:[NSBundle mainBundle]]
                    forCellReuseIdentifier:[self @"cellFromNib"]];
}

C. De-queue the nib's tableViewCell...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFromNib" forIndexPath:indexPath];
    // customize your cell here...
}

D. Add a "dummy" prototype cell to your TableView in your storyboard. Make a segue from this "dummy" cell to the view you want displayed when the cell is selected - make sure to name the segue - I'll call it @"theSegue" for this example. You will reference this segue in your code.

E. Finally, add code to segue from that cell...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // this is basically what the storyboard does under the hood...
    // make sure you have a "dummy" prototype cell with this segue name for each
    // tableview that uses this cell
    [self performSegueWithIdentifier:@"theSegue" sender:self];
}

If you want to specialize your cell code, create a class that subclasses UITableViewCell

I think that is everything you need.

I would say do not be afraid of doing something like this because, if you are serious about IOS programming, you will learn something new. It really does make for much better reusable code.

like image 176
mdebeus Avatar answered Oct 23 '22 08:10

mdebeus