【问题标题】:TapGestureRecognizer is not working in custom TableViewCellTapGestureRecognizer 在自定义 TableViewCell 中不起作用
【发布时间】:2013-02-12 19:29:45
【问题描述】:

我有一个奇怪的问题 - 当我在 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;
}

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

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

【问题讨论】:

  • 更改这一行 [tgr setNumberOfTouchesRequired:1];with [tgr setNumberOfTouchesRequired:2];,它对我有用...

标签: ios ios5 uitapgesturerecognizer


【解决方案1】:

你确定initWithStyle:reuseIdentifier 被调用了吗?如果您为单元格注册笔尖,则必须使用 initWithCoder:

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

- (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 方法中工作。

【讨论】:

  • 谢谢!您的解决方案也很完美!我对你们俩都投了赞成票,但用较低的评分标记了一个。
  • 谢谢!很好的解决方案以及 +1
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多