Ios 如何挂钩UITableViewCell/UICollectionViewCell';s初始化方法?

Ios 如何挂钩UITableViewCell/UICollectionViewCell';s初始化方法?,ios,objective-c,uitableview,uicollectionviewcell,Ios,Objective C,Uitableview,Uicollectionviewcell,我们像这样使用UITableViewCell - (void)viewDidLoad { [super viewDidLoad]; [self.tableView registerNib: [UINib nibWithNibName: Cell bundle: nil] forCellReuseIdentifier: kIdentifier]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRo

我们像这样使用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;
}
当单元格具有某些属性(标记)时,如何获取单元格的
-init
方法、自定义它并标记单元格

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

那么如何钩住UITableViewCell/UICollectionViewCell的
init
方法呢

以下是一种情况:

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


当然,我可以添加属性。再往前走一点。

init
并没有真正的帮助,因为细胞很少被创建,然后被重用

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


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

我建议创建一个简单的
UITableViewCell
子类。通过这种方式,您可以在单元格初始化期间使用希望单元格包含的任何内容创建自定义表格单元格。然后,您可以将nib文件类设置为,例如,
CustomTableViewCell

然后,正如您已经展示的那样,您可以从
重用标识符
创建自定义单元格:

此外,您还可以拦截其他内置方法
awakeFromNib
,甚至
prepareforeuse
进行进一步定制

- (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
毕竟,UITableViewCell是一种类。那么如何从一开始就拦截它。有什么线索吗?不完全确定你的意思:\n也许可以试着再解释一下?
Class*object=[[Class alloc]init],UITableViewCell是从UIView继承的类。苹果为我们做了很多事情。所以我们不知道它是怎么发生的。在我看来,这个过程是存在的。我想知道有没有办法处理。我不知道太多的秘密,所以我问@Gereon提到,确实没有必要“拦截”类的基本对象的创建。。。从我发布的方法来看,你应该能够实现你所需要的。
#import <UIKit/UIKit.h>

@interface CustomTableViewCell : UITableViewCell

- (void)someCustomMethod;
...
@property (nonatomic, nullable) <Some class you want> *somePropertyName;
...
@end
#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