dengApro
dengApro

Reputation: 4038

How to hook a UITableViewCell/UICollectionViewCell's init method?

We use UITableViewCell like this.

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib: [UINib nibWithNibName: Cell bundle: nil] forCellReuseIdentifier: kIdentifier];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *cell = [tableView dequeueReusableCellWithIdentifier: kIdentifier forIndexPath: indexPath];
    return cell;
}

When cells are born with some properties(tag), how to get cell's - init method, customize it, and tag the cell?

As I did not see any chance while calling the relative methods.

So how to hook a UITableViewCell/UICollectionViewCell's init method?

Here is a situation:

img

There are two pages. The cell has a page tag.

Sure, I can add property. Just go a litter farther.

Upvotes: 1

Views: 266

Answers (2)

Gereon
Gereon

Reputation: 17882

init isn't really helpful, since cells are created only rarely and then reused.

That said, when cells are initially created, you can intercept that by overloading awakeFromNib. When they're reused later, prepareForReuse is called.

Don't forget to call the super implementations in both methods.

Upvotes: 1

Will Ullrich
Will Ullrich

Reputation: 2238

I would recommend creating a simple subclass of UITableViewCell. This way you can create customized table cells with whatever you would like the cell to contain "during" the initialization of the cell. Then you could set your nib file class to, for this example, CustomTableViewCell.

Then, like you already have shown, you can just create your customized cells from your reuseIdentifier:

Additionally, you can intercept the other built in methods awakeFromNib and even prepareForReuse for further customization.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: kIdentifier forIndexPath: indexPath];

    // Do anything else here you would like. 
    // [cell someCustomMethod];

    return cell;
}

.h

#import <UIKit/UIKit.h>

@interface CustomTableViewCell : UITableViewCell

- (void)someCustomMethod;
...
@property (nonatomic, nullable) <Some class you want> *somePropertyName;
...
@end

.m

#import "CustomTableViewCell.h"

@implementation CustomTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // Do whatever you would like to do here :)
    }

    return self;

}

- (void)awakeFromNib {

    [super awakeFromNib];

    // Initialization code. Do whatever you like here as well :)

}

- (void)prepareForReuse {

    [super prepareForReuse];

    // And here.. :)

}

@end

Upvotes: 1

Related Questions