Reusable UITableView Prototype Cell

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

+6
source share
1 answer

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

a. add nib file:
1. Select New File ... 2. Select IOS โ†’ User Interface
3. Select "Empty" โ†’ this will add a new .xib file to your project
4. Drag the UITableViewCell from the object browser to your xib file and configure as you wish
5. Use the Utilities panel to change properties โ†’ editing a tip is very similar to editing a storyboard.
6. Make sure you name the cell โ€” I chose the name cellFromNib, but you probably want something else.

C. Load a UITableViewCell into each tableDidLoad method of the table:

- (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 nib tableViewCell ...

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

D. Add the โ€œdummyโ€ prototype to your TableView in your storyboard. Make a selection from this cell "dummy" in the view that you want to display when the cell is selected - be sure to specify a name - I will call it @ "TheSegue" for this example. You will reference this segue in your code.

E. Finally, add code to highlight from this 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 all you need.

I would say donโ€™t be afraid to do something like this, because if you are serious about iOS programming, you will learn something new. It really makes much better reusable code.

+9
source

All Articles