我能做到吗?
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;
}
}
最佳答案
从您显示的代码来看,您的 oneLabel
和 twoLabel
从未被初始化。如果您想快速修复,可以将它们都替换为 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
}
}
您将能够在表格 View 中看到两个不同部分的不同文本。它们确实是不同的 TableviewCell
类。
但是,如果您想为不同的 UITableViewCell
使用不同的标签,那么您必须确保它们在某处以某种方式进行了初始化。例如,您可以覆盖自定义表格 View 单元格中的默认 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
关于ios - 如何为不同的 UITableView 部分使用不同的 TableView 单元格类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394711/