如何挂钩 UITableViewCell/UICollectionViewCell 的初始化方法?

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

我们这样使用 UITableViewCell。

- (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;
}

细胞天生带有一些属性(tag),如何获取细胞的- init方法,自定义,标记细胞?

因为我在调用相关方法时没有看到任何机会。

那么如何挂钩 UITableViewCell/UICollectionViewCell 的 init 方法?

这是一种情况:

有两页。该单元格有一个页面标记。

当然可以,我可以添加 属性。再远一点就可以了

init 并没有太大帮助,因为单元格很少被创建,然后被重复使用。

也就是说,当最初创建单元格时,您可以通过重载 awakeFromNib 来拦截它。稍后重用它们时,将调用 prepareForReuse

不要忘记在两种方法中调用超级实现。

我建议创建一个 UITableViewCell 的简单子 class。通过这种方式,您可以创建自定义的 table 单元格,其中包含您希望单元格包含 "during" 单元格初始化的任何内容。然后你可以将你的 nib 文件 class 设置为,例如,CustomTableViewCell

然后,就像您已经展示的那样,您可以从 reuseIdentifier:

创建自定义单元格

此外,您可以拦截其他内置方法 awakeFromNib 甚至 prepareForReuse 以进一步自定义。

- (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