Duck
Duck

Reputation: 35933

How do I use a UITableView cell and its elements on prototype cell

I have started a new iPad project using this Master-Detail application. I am not a huge fan of creating stuff using Interface Builder, but for this project in particular I have to use that.

I need to create a custom cell to use on the MasterViewController. This cell will contain a switch and a label. Using interface builder, I have dragged these elements to what is called Prototype Cells inside what is called TableView Prototype Content.

This is what I get.

enter image description here

Now how do I use that inside tableView:cellForRowIndexPath:? Do I have to have outlets to use that UILabel and UISwitch? How do I do that?

thanks

Upvotes: 0

Views: 292

Answers (3)

Pancho
Pancho

Reputation: 4143

First create UITableViewCell subclass and set it to your Prototype Cell in Storyboard. Second Give your Prototype cell a reuse identifier in Storyboard. Create IBOutlet of your UILabel and UISwitch in your newly created subclass of UITableViewCell Import your custom cell class into your viewcontroller.m file In your cellForRowAtIndexPath: method dequeue your custom cell

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 static NSString *cellID = @"cell"; // identifier you have entered in storyboards
 CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

 if(!cell)
 {
  cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
 }

 //access your custom cell properties from now on
 cell.mySwith // or whatever name you gave it in your outlet

 return cell;

}

Upvotes: 0

William George
William George

Reputation: 6785

You need to give the cell a Reuse Identifier in Interface Builder after which you will be able to access the cell via:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Without subclassing you can give each element inside the cell a tag and use:

UISwitch *checkSwitch = (UISwitch *)[cell viewWithTag:-1];

Upvotes: 1

Cezar
Cezar

Reputation: 56322

Yes. You should create a UITableViewCell subclass, and add IBOutlets for each control you'll need access to. Then, you set your subclass as the custom Class for each prototype cell in the identity inspector.

You'll also need to set the reuse identifier. Then, you can dequeue cells as you would normally do in tableView:cellForRowIndexPath::

YourCustomCellClass *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Upvotes: 1

Related Questions