nmokkary
nmokkary

Reputation: 1239

Can't access to label in prototype cell in UITableView

This is my code :

@implementation NViewController{
    NSArray *recipes;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    recipes = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];

    return cell;
}

@end

i add a label to content view in prototype tableviewcell but can't access to it (txtname). please show me a solution

Upvotes: 1

Views: 2885

Answers (2)

Greg
Greg

Reputation: 25459

You can set up tag (for example 100) to the label in storyboard and in cellForRowAtIndexPath: method before you return cell you cat get reference to that label by tag

UILabel *taggedLabel =(UILabel*) [cell.contentView viewWithTag:100]; 
taggedLabel.text = [recipes objectAtIndex:indexPath.row];

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

When you add a label to your prototype cell, and wish to access that label through your code, you need to do the following as well:

  • Define a class for your custom cell, extending UITableViewCell
  • Add an IBOutlet property txtname for your label in the custom cell class
  • Establish a connection between the outlet property and the label (e.g. by command-dragging)
  • Set the type of your custom cell to the properties of your prototype cell in the storyboard
  • Change the code to reference your custom cell type instead of UITableViewCell

The last step changes your code as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";
    MyCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[MyCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.txtname.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}

Upvotes: 3

Related Questions