Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UITableViewCell using storyboard and subclass

I have created a subclass of UITableViewCell and I called it DCCustomCell. This is the DCCustomCell.h file.

#import <UIKit/UIKit.h>

@interface DCCustomCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UILabel *price;

@end

All the proprieties are correcty connected with elements in my iPhone.storyboard file. I also selected the tableViewCell in iPhone.storyboard and i setted my cell's identifier to "CustomCell" and the class to DCCustomCell.

This is the UITableViewController's viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

    // Do any additional setup after loading the view, typically from a nib.
}

and this is the tableView:cellForRowAtIndexPath: method:

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

    DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

    NSLog(@"%@" ,cell);

    cell.imageView.image = [UIImage imageNamed:@"info_button.png"];
    cell.title.text = @"Hello!";
    cell.date.text = @"21/12/2013";
    cell.price.text = @"€15.00";

    return cell;
}

The problem is that the imageView is correctly setted, but all the labels are blank. If I change the imageView property name to, for example, eventImageView, the image will not be setted. This is the result:

enter image description here

I can't figure out how I can solve this problem.

EDIT: if I remove

[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

from viewDidLoad all seems to work. why?

like image 850
Marco Manzoni Avatar asked Nov 29 '13 10:11

Marco Manzoni


2 Answers

As you noticed it works when you remove

[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

You only have to do this if you use dequeueReusableCellWithIdentifier:indexPath: AND have not already set the custom class in the identity inspector for that cell. If you use registerClass: forCellReuseIdentifier the cell will be initialized with initWithStyle:reuseIdentifier: instead of initWithCoder: thus screwing up your connections you made in the storyboard.

like image 51
Jay V Avatar answered Oct 11 '22 16:10

Jay V


Have you bind the Controls to IBOutlet ? You can try setting DCCustomCell to UITableviewCell's class directly in Storyboard. And than you need to set outlets with controls in cell

like image 27
Samir Avatar answered Oct 11 '22 17:10

Samir