1
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
        //[self createViews];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    NSLog(@"draw rect");
    [self createViews];
}

I'm creating a custom UITableViewCell. I require creating a UILabel that depends on the height of the UITableViewCell, and the height is not yet set in initWithStyle (it returns the default 44 when in reality the height of my cell varies greatly). For this reason, I call my createViews function in drawRect. This was working well, however I'm noticing that the function can be called again when I insert and delete rows.

My Question: Does it make sense to call my createViews function inside drawRect?

3
  • I wouldn't recommend doing it in drawRect. How are you getting your cell height? Why not use auto layout and your cell doesn't need to worry about its height. Commented Sep 19, 2015 at 20:57
  • 1
    No. drawRect should not be used to create views. Commented Sep 19, 2015 at 20:57
  • @rmaddy where should I create my views then if I'm not using autolayout? Commented Sep 19, 2015 at 23:15

1 Answer 1

1

You have few options here.

1. Use layoutSubviews/awakeFromNib, check whether the subviews were created, if no, create them with correct frames.

2. Use init to create views with:

  • Constraints
  • Without constraints and in layoutSubviews/awakeFromNib try to change the frame
Sign up to request clarification or add additional context in comments.

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.