【问题标题】:why init method in cell won't get called when dequeueReusableCellWithIdentifier happened为什么当 dequeueReusableCellWithIdentifier 发生时单元格中的 init 方法不会被调用
【发布时间】:2019-11-11 09:42:23
【问题描述】:

我的代码是这样的

viewcontroller.m

- (void)viewDidLoad {
    [super viewDidLoad];

    UITableView *tableView = [[UITableView alloc] init];

    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = @"Hello, world";
    cell.delegate = self;
    return cell;
}

细胞.m

- (void)awakeFromNib {
    [super awakeFromNib];
    [self commonInit];
    // Initialization code
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress)];
    [self addGestureRecognizer:longPress];
}


- (void)longPress
{
    [self.delegate actionTriggered:self];
}

所以屏幕显示了一个只有一个单元格包含“hello world”的表格视图 使用长按手势时没有任何反应。

所以我在 commonInit 中设置了一个断点。 找出这个方法没有被调用。 不知道为什么。以及如何解决它。 感谢任何帮助。

【问题讨论】:

标签: ios objective-c uitableview


【解决方案1】:

在“viewDidLoad”中创建一个局部变量“tableView”。一旦方法完成,该变量就会超出范围。

这行不通。

假设你的 viewcontroller.m 文件中的类继承自 UITableViewController 你只需要确保你配置了现有的 tableView 属性而不是创建一个局部变量:

-(void)viewDidLoad {
    [super viewDidLoad];

    // UITableView *tableView = [[UITableView alloc] init];  <-- Don't!

    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    相关资源
    最近更新 更多