如何创建类变量



我在表视图中使用不同的单元格,所以我想创建它们取决于某些方面。但创建代码是相同的,只是类名不同。如何让它变得更好?也许创建一些变量id classname = (indexPath.section > 3) ? FirstCell : SecondCell;

if (indexPath.section >3)
{
    FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(FirstCell.class)];
    if (!cell)
        cell = [[FirstCell alloc] initWithStyle:UITableViewCellStyleDefault
                                reuseIdentifier:NSStringFromClass(FirstCell.class)];
    return cell;
}
else
{
    SecondCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(SecondCell.class)];
    if (!cell)
        cell = [[SecondCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:NSStringFromClass(SecondCell.class)];
    return cell;
}

只是一个建议,在这种情况下我使用了不同的apprach。我将单元格创建代码移动到相应的tableviewcell类中。

@implementation FirstCell
+ (FirstCell *) cellForTableView:(UITableView *)aTableView
{
   FirstCell *cell = [aTableView dequeueReusableCellWithIdentifier:NSStringFromClass(FirstCell.class)];
   if (!cell)
   {
      cell = [[FirstCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(FirstCell.class)];
   }
   return cell;
}
@end

cellForIndexPath方法的形式如下,

if (indexPath.section > 3)
    return [FirstCell cellForTableView:tableView];
return [SecondCell cellForTableView:tableView];

这对你有用吗?

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[FirstCell class] forCellReuseIdentifier:NSStringFromClass([FirstCell class])];
    [_tableView registerClass:[SecondCell class] forCellReuseIdentifier:NSStringFromClass([SecondCell class])]; //ios 6 and above
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = (indexPath.section > 3) ? NSStringFromClass([FirstCell class]) : NSStringFromClass([FirstCell class]);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //cell is guaranteed not to be nil if you register it before
    return cell;
}

你的意思是这样的吗?

Class class = (indexPath.section > 3) ? FirstCell.class : SecondCell.class;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(class)];
if (!cell)
    cell = [[class alloc] initWithStyle:UITableViewCellStyleDefault
                        reuseIdentifier:NSStringFromClass(class)];
return cell;

最新更新