2014-09-03 74 views
0

我有类层次与loadNibNamed在基类覆盖儿童实例

ParentCell extends UITableViewCell 
ChildCell extends ParentCell 

ParentCell具有单独的XIB,在子小区i被创建并在ParentCell XIB添加只有一个按钮到一个视图。但我不能添加此按钮的操作。因为即使我为ChildCell创建了一个实例,它也会返回ParentCell的实例

因为我使用loadNibNamed来获得带有IBOutlet连接的XIB。 @在ChildCell类在ParentCell类

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     self = [[NSBundle mainBundle] loadNibNamed:@"ParentCell" owner:self options:nil] 
       [0]; 
    } 
    return self; 
} 

initWithStyle方法@ initWithStyle方法

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     self.button=[[UIButton alloc] init]; 
     [self.contentView addSubview:button]; 
    } 
    return self; 
} 

@ - 视图 - 控制器

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
      static NSString *CellIdentifier = @"ChildCell "; 
      ChildCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
      if (cell == nil) 
      { 
       cell=[[ChildCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

       NSLog(@"Cell : %@", cell); //this have instance of ParentCell instead of ChildCell 
      } 
} 

现在,通过这种方式

暂时解决@initWithStyle方法ParentCell类

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     NSBundle *mainBundle = [NSBundle mainBundle]; 
     NSArray *views = [mainBundle loadNibNamed:@"ParentCell" 
              owner:self 
              options:nil]; 
     //Here we are linking the view with appropriate IBOutlet by their tag 
     self.lblTitle=[views[0] viewWithTag:100]; 
     self.lblContent=[views[0] viewWithTag:200]; 
    } 
    return self; 
} 

@ initWithStyle方法ChildCell类

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     self.button=[[UIButton alloc] init]; 
     [self.contentView addSubview:button]; 
    } 
    return self; 
} 

但我不知道这是遵循正确的方法,或者我们有一些其他更好的方法,然后这个..

回答

1

你应该在你的UITableView类的viewDidLoad上使用registerNib:forCellReuseIdentifier:方法。

static NSString *parentCellIdentifier = @"parentCellIdentifier"; 
static NSString *childCellIdentifier = @"childCellIdentifier"; 

[self.tableView registerNib:[UINib nibWithNibName:@"ParentCell" bundle:nil] forCellReuseIdentifier:parentCellIdentifier]; 
[self.tableView registerNib:[UINib nibWithNibName:@"ChildCell" bundle:nil] forCellReuseIdentifier:childCellIdentifier]; 

(不要忘记设置相应的ReuseIdentifier在XIB文件)

这是最好的做法,你可以摆脱你的initWithStyle实现。