【问题标题】:UITapGestureRecognizer for a custom cell in UITableViewUITableView 中自定义单元格的 UITapGestureRecognizer
【发布时间】:2014-08-13 13:40:19
【问题描述】:

在我的 iPhone 应用程序中,我通过子类化 UITableViewCell 来使用带有自定义表格单元格的 UITableView。假设我的自定义单元格类名称为 ItemTableViewCell。相关的 ItemTableViewCell.xib 有一个名为 infoView 的子视图 UIView

我希望 infoView 识别它所获得的单击/触摸。如果只是点击,我可以通过使用故事板添加UITapGestureRecognizer 并为此设置操作方法来实现。但是我需要的是在识别 infoView 的点击/触摸时,我需要将相关的表格行信息传递给目标方法/选择器。

如果我进一步解释这种情况,UITableViewNSArrayUITableViewCell 组成。该自定义单元格的底部栏带有一个名为 infoView 的子视图。通过点击/触摸 infoView,它应该调用一个以相关 NSArray 元素作为参数的方法。通过点击/触摸单元格的其余部分,它应该像往常一样调用didSelectRowAtIndexPath 方法。

【问题讨论】:

  • 使用委托模式让您的单元格在被点击时通知控制器。

标签: ios uitableview uitapgesturerecognizer didselectrowatindexpath


【解决方案1】:

我找到了解决办法。在创建自定义单元格时,我将 UITapGestureRecognizer 添加到相关的 UIVIew(在我的情况下是 infoView),如下所示。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedOnInfoView:)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[cell.infoView addGestureRecognizer:tap];
[cell.infoView setUserInteractionEnabled:YES];
[cell.infoView setTag:realIndex];

从最后一行可以看出,我将单元格索引而不是单元格数据传递给选择器,该选择器将在识别轻击手势后触发。

同时我正在维护一个 NSMutableArray 来存储单元格的数据。正如您所理解的,每个单元格索引都会同时存在 NSArray 元素。

这就是我的选择器的显示方式;

- (void)tappedOnInfoView:(UIGestureRecognizer *)sender {

通过使用下面的代码,您可以获得与发生的点击手势相关的索引

sender.view.tag

使用跟随代码 sn-p 我可以获取存储在 NSMutableArray 中的单元格的详细信息

[myMutArray objectAtIndex:sender.view.tag];

任务完成:)

【讨论】:

    【解决方案2】:

    在 Tableview SuperClass 中实现手势动作。或者您可以在 UITableViewCell 子类中使用自定义委托。在 UITableView 的子类中声明一个协议。

    @protocol customCellDelegate <NSObject>
    
    @required
    -(void)selectedCellInIndexPath : (NSIndexPath *)indexpath;
    @end
    

    在 UITableView 子类中设置该属性

    @property (nonatomic, strong)NSIndexPath *indexpath;
    @property (nonatomic, strong) id <customCellDelegate> delegate;
    

    然后在你的 UITableView 子类手势动作中添加这行

    if(self.delegate){
       [self.delegate selectedCellInIndexPath: self.indexpath];
    }
    

    在你的 tableview 数据源方法中

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    

    实现这段代码

    cell.delegate = (id)self;
    cell.indexpath = indexPath;
    

    在 Uitableview 超类中实现这个方法

    -(void)selectedCellInIndexPath : (NSIndexPath *)indexpath{
    //display uiimagepickercontroller modally or anything else here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多