简体   繁体   中英

Setting variables in UITableViewCell subclass

I have a UITableViewCell subclass I need to have two UIColor variables in. I've declared them in the header but where in the implementation would I set their values for access later?

I need a similar method to viewDidLoad so that I can set these when the cell loads. I have tried setting them in initWithStyle but its no good as I don't use that to create my cells.

In my view controller I load them in like below:

CustomCell *cell = [tv dequeueReusableCellWithIdentifier:cellIdentifier];

So where would I set these variables? (I want to try and keep them inside the subclass.)

Edit

Here is my cellForRowAtIndexPath method:

- (CustomCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";

    CustomCell *cell = [tv dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    return cell;
}

If you're using storyboards and prototypes, then your cell will have awakeFromNib called on it when first created. You can put your code in here.

initWithStyle: is not called because your cell is being loaded from a nib. It will be initialised using initWithCoder: instead. You could put your code there as well, or in a shared setup method called from there and initWithStyle (if you change the way you use the cells in the future).

initWithStyle is the designated initializer for UITableViewCell classes so you have to use that method to init a UITableViewCell. Dequeing only works if you have init your cell and there are cells available to dequeue.

You can see your code that you alloc and init if the cell is nil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM