0

我创建了大量的 UITableViewCell 子类。每一个都是额外的 BGBaseTableViewCell 类的子类。

当被问及高度时,我认为告诉用户 UITableViewCell 的典型大小是多少会很有用。

一种方法是指定两次。

一次是我在 xib 中设计 UITableViewCell,第二次是我硬编码典型尺寸。

这是一个设计缺陷,因为当我在 xib 中更改内容时,我需要记住更改硬编码的典型大小。

我不想要那个。我想在 xib 中设计我的 UITableViewCell 并且在初始化类时我想存储默认高度。

所有子类的默认高度需要不同。但是,对于该子类的所有实例,它必须相同。

如果我使用简单的 ivar,那么我将不得不为所有实例存储一个默认大小。

如果我使用静态变量,那么 BGBaseTableViewCell 中的静态变量将被它的所有子类使用。

所以我该怎么做?

这就是我现在正在做的事情:

static CGFloat defaultHeightSet = 0; //this one is used by all subclasses. I want each subclass have it's own defaultHeightSet, but I want to specify that fact once.

+(void)initialize
{
    BGBaseTableViewCell * typical = [[self alloc]init];
    defaultHeightSet = typical.bounds.size.height;
}
+(CGFloat) defaultHeight
{
    return defaultHeightSet;
}
4

2 回答 2

2

在整个班级中可见但对子班级不可见?您可以为您的 .m 文件尝试此代码:

@interface ClassYouNeed ()
static VariableClass* variableVisibleInClassButNotInSubclass;
@end

只需在您的实现附近的类上创建一个“隐藏”类别,它应该可以工作。

于 2012-12-06T09:01:26.743 回答
0

为什么我没有想到。

使静态变量成为字典并将类名设置为键:)

女士们先生们,各个年龄段的孩子们。Sharen Eayrs 的产品自豪地展示了静态保护的变量:

static NSMutableDictionary * defaultHeightDictionary= nil;
static NSMutableDictionary * defaultBoundsDictionary =nil;
//static CGFloat defaultHeightSet = 0;

+(void)initialize
{
    BGBaseTableViewCell * typical = [[self alloc]init];

    if (defaultHeightDictionary==nil) {
        defaultHeightDictionary = [NSMutableDictionary dictionary];
        defaultBoundsDictionary = [NSMutableDictionary dictionary];
    }
    [defaultHeightDictionary setValue:@(typical.bounds.size.height) forKey:NSStringFromClass([self class])];
    CGRect bounds = typical.bounds;

    NSValue * boundsValue = [NSValue valueWithCGRect:bounds];
    [defaultHeightDictionary setValue:boundsValue forKey:NSStringFromClass([self class])];


}
+(CGFloat) defaultHeight
{
    NSNumber * result = [defaultHeightDictionary valueForKey:NSStringFromClass([self class])];
    return result.floatValue;
}

+(CGRect) defaultBounds
{
    NSValue * result = [defaultBoundsDictionary valueForKey:NSStringFromClass([self class])];
    return [result CGRectValue];
}
于 2012-12-06T07:12:02.713 回答