0

我有一个奇怪的问题 - 当我在 cellForRowAtIndexPath 方法中注册 TapGestureRecognizer 时,它工作得很好,但是当我在单元格的 initWithStyle 方法中注册 TapGestureRecognizer 时,点击识别不起作用,断点不会在处理程序中命中。

以下作品。

我已经使用相应的 xib 文件创建了自定义表格视图单元并注册了它。

[self.tableView registerNib:[UINib nibWithNibName:@"MyCell"
                                               bundle:[NSBundle mainBundle]]
         forCellReuseIdentifier:@"cell"];
...

and in the cellForRowAtIndexPath 
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
...
 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(didTapCell:)];
    [tap setNumberOfTapsRequired:1];
    [cell addGestureRecognizer:tap];

以下不起作用

@implementation MyCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCellTap:)];
        [tgr setDelegate:self];
        [tgr setNumberOfTapsRequired:1];
        [tgr setNumberOfTouchesRequired:1];

        [self addGestureRecognizer:tgr];
        //[self.contentView addGestureRecognizer:tgr]; also doesn't work
    }
    return self;
}

我可以离开工作解决方案,但我想通过我的委托将手势识别移动到单元初始化和触发点击事件。

如果我在单元初始化中注册识别器,为什么点击识别不起作用?

4

2 回答 2

2

你确定initWithStyle:reuseIdentifier叫?initWithCoder:如果您为单元注册笔尖,则必须使用 Afaik 。

在我的一个项目中,我有这个

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        pan.delegate = self;
        self.gestureRecognizers = [NSArray arrayWithObject:pan];
    }
    return self;
}

所以我使用的是平移手势识别器,它在 init 方法中工作。

于 2013-02-12T11:29:45.470 回答
1

您已为特定单元格标识符注册了 xib。现在,如果需要,tableview 将自动为您实例化一个单元格(当您调用 dequeReusableCell 时...),但不会调用 initWithStyle:reuseIdentifier 方法,因此永远不会创建/添加您的手势识别器。

如果您在使用已注册的 xib 时确实需要“初始化”东西,请覆盖自定义单元类中的 awakeFromNib 并将您的代码放在那里。我通常将我的“init”代码放在一个单独的方法中,并从 initWithStyle 和 awakeFromNib 覆盖中调用它。

于 2013-02-12T11:29:38.773 回答