Snowman
Snowman

Reputation: 32081

Custom UITableViewCell Question

I've created a custom cell class using these instructions: http://www.bdunagan.com/2009/06/28/custom-uitableviewcell-from-a-xib-in-interface-builder/

Now, I have two view controllers: MyPostsViewController and CustomCellViewController. The custom cell is just a cell with a UITableViewCell and has two labels declared and connected. The MyPostsViewController is a UITableView that uses these custom cells. However, I am unsure how to access the two labels of the CustomCellViewController from the MyPostsViewController. I want to access them from the MyPostsViewController because that is where the cellForRowAtIndexPath method is and where I want to set the value of my labels at. How would I do this?

Upvotes: 0

Views: 85

Answers (3)

Nathanial Woolls
Nathanial Woolls

Reputation: 5291

I think the cleanest way to do this is to define IBOutlets on your custom UITableViewCell subclass. Then, when designing your XIB, CTRL+click your custom cell. You should see the outlets there. Drag-drop to hook up your outlets to your labels, just like you normally would with views. Finally, access those IBOutlets in your cellForRowAtIndexPath method.

Upvotes: 1

Akshay
Akshay

Reputation: 5765

You should customize (set the values for your labels) in cellForRowAtIndexPath:. To do this, you can set tags for your labels in IB itself (find the tag field in the Attributes inspector). Let's say you set 1 for Label1 & 2 for Label2. Then, your code would look something like (copying from the link you posted)-

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BDCustomCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }

//customize the cell here
UILabel* label 1 = [cell viewWithTag:1];
label1.text = @"my text";

//similarly label 2

    return cell;
}

HTH,

Akshay

Upvotes: 1

Cyrille
Cyrille

Reputation: 25144

You don't need a CustomCellViewController if you follow the instructions you posted. Just load your cells from your NIB in your MyPostsViewController.

To access individual subviews of your cell, give them each a distinctive tag, then retrieve them with [cell viewWithTag:42], for example.

Upvotes: 1

Related Questions