UITableViewCell - Best place to set up the cell

后端 未结 3 511
独厮守ぢ
独厮守ぢ 2021-01-01 00:50

I\'ve been playing around with custom cells in a UITableViewController by have a base cell (BaseCell - subclass of UITableViewCell) and then subclasses of BaseCell (Sub1Cell

相关标签:
3条回答
  • 2021-01-01 01:04

    You can use awakeFromNib in your cell subclasses. This will be called when a new cell is created from the prototype in your storyboard, but not when a cell is re-used.

    If you are using prototypes then the whole if (cell == nil) thing goes away, UITableView handles all that for you within the dequeue method.

    0 讨论(0)
  • 2021-01-01 01:11

    In the custom cell class, provide a init method, to initialize. some codes like below:

    - (id)initWithReuseIdentifier:(NSString *)cellIdentifier
    {
        if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier])
        {
            self.picture.layer.cornerRadius = 5.0f;
            self.picture.layer.masksToBounds = YES;
            self.picture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            self.picture.layer.borderWidth = 1.0f;
        }
        return self;
    }
    
    0 讨论(0)
  • 2021-01-01 01:13

    That looks ok. As long as you're only calling it at cell creation rather than in every pass through tableView:cellForRowAtIndexPath:. Not sure which you're doing from your sample code.

    You might try to put your code in your custom cell's drawRect: to see what happens. Note that this can get tricky for custom cells; you might need to think about customizing layoutSubviews as well.

    Also, for what it's worth, setting those particular CALayer properties can have a slowing effect due to offscreen rendering, but I think it won't be a big deal for you, as if should only be happening at cell creation.

    UPDATE

    I think you will want to separate the initial setup code from the code that updates the content of the cell during table view operation. The initial setup code, which it seems to me is what you've written above, should only be run once, at cell creation. So I'm taking back what I wrote in the 2nd paragraph, above; don't put it in drawRect:.

    MORE

    Check out Apple's docs here. I'm not sure the effect of passing cell style... if in your override of initWithStyle:reuseIdentifier: you pass the style to super, then yes, I would think that super would use it to set up the cell's content view. If you then modify the content view with your own stuff, then super is doing wasted work. As for the rest of the code you added under 'Edit:', I think it looks good.

    For what it's worth, whenever I do this, I use InterfaceBuilder.

    0 讨论(0)
提交回复
热议问题