在TableViewCell上使用tapgesture弹出窗口

时间:2013-02-26 10:33:39

标签: objective-c popup cgpoint

我有一个包含多个标签的自定义单元格的TableView。我在其中一个标签上添加了一个tapgesture,因此会出现一个弹出窗口。问题是,弹出窗口不会出现在应有的位置(居中并位于标签顶部)。

这条线有什么问题:

[self.popupMenu showInView:self.view atPoint:CGPointMake(label.center.x, label.frame.origin.y)];

tableview.m:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // add a tap gesture recognizer
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap:)];
    [cell.customAmountLabel addGestureRecognizer:tapGesture];

    NSString *ItemName = [NSString stringWithCString:CurrentOrder[indexPath.row].c_str() encoding:NSUTF8StringEncoding];
    NSString *ItemAmount = [NSString stringWithCString:CurrentOrder[indexPath.row].c_str() encoding:NSUTF8StringEncoding];

    cell.customNameLabel.text = ItemName;
    cell.customAmountLabel.text = ItemAmount;

    return cell;
}

点按手势的方法:

- (void)labelTap:(UITapGestureRecognizer *)gestureRecognizer
{
    // get location of the swipe
    CGPoint location = [gestureRecognizer locationInView:self.tableCurrentOrder];

    // get the corresponding index path within the table view
    NSIndexPath *indexPath = [self.tableCurrentOrder indexPathForRowAtPoint:location];

    // check if index path is valid
    if(indexPath)
    {
        // get the cell out of the table view
        CustomCell *cell = (CustomCell *) [self.tableCurrentOrder cellForRowAtIndexPath:indexPath];

        // update the cell or model
        std::cout << CurrentOrder[indexPath.row] << std::endl;

        UILabel *label = (UILabel *)cell.customAmountLabel;

        [self.popupMenu showInView:self.view atPoint:CGPointMake(label.center.x, label.frame.origin.y)];
    }
}

1 个答案:

答案 0 :(得分:1)

点击单元格后,是否要弹出任何视图?如果是,那么我建议您在CustomCell类中使用-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event方法。

您将能够知道点击使用方法的event参数的位置。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet *allTouches = [event allTouches]; 
    for (UITouch *touch in allTouches) 
    { 
        CGPoint location = [touch locationInView:touch.view];
        (...)
    }
}