我们像这样使用 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
方法,自定义它,并标记单元格?因为我在调用相关方法时没有看到任何机会。
那么如何 Hook UITableViewCell/UICollectionViewCell 的
init
方法?这是一种情况:
有两页。该单元格有一个页面标签。
当然,我可以添加属性。走得更远一点。
最佳答案
我建议创建 UITableViewCell
的简单子(monad)类.这样,您可以使用您希望单元格在“初始化”单元格期间包含的任何内容来创建自定义表格单元格。然后您可以将您的 nib 文件类设置为,例如,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
关于ios - 如何 Hook UITableViewCell/UICollectionViewCell 的 init 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48345184/