0

I have a UITableViewCell called fatherCell and its nib file,to make code reusable,then I inherit fatherCell by creating childCell without nib file.But I don't know how to make a correct connection from childCell to fatherCell's nib. here is the code:

FatherCell and childCell

@interface FatherCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
- (IBAction)cellBtnPressed:(id)sender;

@end


@implementation FatherCell

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.titleLabel.text = @"fatherTitle";
}

- (IBAction)cellBtnPressed:(id)sender
{
    NSLog(@"call father method");
}

@end

@interface ChildCell : FatherCell

@end


@implementation ChildCell


- (void)awakeFromNib
{
    [super awakeFromNib];

    self.titleLabel.text = @"childTitle";

}

- (IBAction)cellBtnPressed:(id)sender
{
    NSLog(@"call child method");
}

@end

Then how to call in the UITableViewController? I use following code,but unfortunately I can't get expected result,only called fatherCell's method

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

    ChildCell *cell = (ChildCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FatherCell" owner:self options:nil] objectAtIndex:0];

}


return cell;

}

Can somebody help me?

Paulw11
  • 108,386
  • 14
  • 159
  • 186
passol
  • 195
  • 4
  • 12
  • http://stackoverflow.com/questions/1236434/how-to-cast-class-a-to-its-subclass-class-b-objective-c – liaogang May 06 '14 at 01:28
  • If you have several subclasses of the father cell, you should create .xib for each subclass. The father cell should only deal with common logic. – Danyun Liu May 06 '14 at 01:48

1 Answers1

0

The object class for the cell is specified in the nib file (The custom class field), so if you use FatherCell.xib you will always end up with a FatherCell object.

You will need to copy your FatherCell.xib to another xib file and change the cell class in the copy.

You could possibly look at abstracting the custom methods out from the cell view class into a controller class, possibly through the use of delegation or blocks, that way you would only need a single cell class and behaviour would be modified by providing an appropriate delegate or handler block.

Paulw11
  • 108,386
  • 14
  • 159
  • 186