0

I have a parent class like this :

@interface SGBaseTableViewCell : UITableViewCell

+ (CGFloat)defaultHeight;
...

@end

The SGBaseTableViewCell is the parent class for all my custom UITablelViewCell

@implementation SGBaseTableViewCell : UITableViewCell

+ (CGFloat)defaultHeight {

    static CGFloat defaultHeight = 0.0;

     static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        SGBaseTableViewCell *cell = [[self class] newDefaultCell]; // newDefaultCell will just load the cell from a xib
        defaultHeight = cell.height;
    });
    return defaultHeight;
 }
@end

I would like that each custom cell will returns it's height. The problem of my code is that it will always return the same height for each cell ( will return the first cell's height).

Is there a solution that each cell will return it's height without overriding in the child class the defaultHeight method ?

PS : I know that i can override the defaultHieght method in each subclass to return the appropriate height, but i would like to know if i can do it juts in the base class ?

Tnaks

14
  • When you mean "the same height for each cell", you mean for each subclass of your cell or for each cell in a tableView (you may have cells with multi-lined labels) ? Commented Jul 2, 2014 at 9:48
  • What happens if you use UITableViewCell *cell = [[self class] newDefaultCell];? Commented Jul 2, 2014 at 9:51
  • @Tanguy of corse you can, in a class method self is the Class Commented Jul 2, 2014 at 9:55
  • 1
    Then I have no more idea :/ Sadly I always override my +(CGFloat)height in cell subclass. Commented Jul 2, 2014 at 12:08
  • 1
    @Tanguy i have answered my question, if you are interested :) Commented Jul 3, 2014 at 13:08

2 Answers 2

1

My final solution (proposed in an other forum) :

+ (CGFloat)defaultHeight
{
    static dispatch_once_t onceToken;
    static NSMutableDictionary *heights;

    dispatch_once(&onceToken, ^{ heights = [NSMutableDictionary new]; });

    @synchronized(self)
    {
        NSString *key = NSStringFromClass(self);
        NSNumber *h = heights[key];
        if (h) return [h floatValue];
        SGBaseTableViewCell *cell = [self newDefaultCell];
        [heights setValue:@(cell.height) forKey:key];
        return cell.height;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I found this article from RayWenderlich: Dynamic tableViewCell auto-layout

It seems to be a good alternative solution and you won't have to override any method for each subclass.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.