2015-02-08 26 views
1

我可以实现这一目标吗?如何为不同的UITableView部分使用不同的表格视图单元格类别

if (indexpath.section == 0) { 
    // Use Class 1 
} else if (indexpath.section == 1) { 
    // Use Class 2 
} 

我试过,但没有工作

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    // Return the number of sections. 
    return 2; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    // Return the number of rows in the section. 
    return 1; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0) { 
     OneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"One" forIndexPath:indexPath]; 
     if(cell == nil){ 
      cell = [[OneTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"One"]; 
     } 
     cell.oneLabel.text = @"HAHAHA"; 
     return cell; 
    }else{ 
     TwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Two" forIndexPath:indexPath]; 
     if(cell == nil){ 
      cell = [[TwoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Two"]; 
     } 
     cell.twoLabel.text = @"HEHEHE"; 
     return cell; 
    } 
} 
+0

解释什么是不工作。 – Wain 2015-02-08 14:10:22

+0

您是否使用正确的标识符在“UITableView”中注册了每个类? – tbaranes 2015-02-08 14:19:51

回答

1

从您展示这些代码,您oneLabeltwoLabel永远不会初始化。如果你想快速修复,你可以用textLabel替换它们。如下所示,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0) { 
     OneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"One" forIndexPath:indexPath]; 
     if(cell == nil){ 
      cell = [[OneTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"One"]; 
     } 
     cell.textLabel.text = @"HAHAHA"; // Modified 
     return cell; 
    } else { 
     TwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Two" forIndexPath:indexPath]; 
     if(cell == nil){ 
      cell = [[TwoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Two"]; 
     } 
     cell.textLabel.text = @"HEHEHE"; // Modified 
    } 
} 

而且您将能够在表格视图中看到两个不同部分的不同文本。他们确实不同TableviewCell类。

但是,如果您想为不同的UITableViewCell使用不同的标签,那么您必须确保它们在某处以某种方式初始化。例如,您可以覆盖自定义表格视图单元格中的默认UITableviewCell初始值设定项。例如,在您的OneTableViewCell.m文件中,在@implementation@end之间添加以下内容。在这种情况下,您可以在UITableView类中使用您的原始代码。

@implementation OneTableViewCell 

- (instancetype)initWithStyle:(UITableViewCellStyle)style 
       reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
      _oneLabel = [[UILabel alloc] init]; 
      [self.view addSubView:self.oneLabel]; 
    } 
    return self; 
} 

@end 
相关问题