0

在我的 ipad 应用程序中,我需要拖放 aUIButton来插入一个单元格。我设法通过 touchupinside 事件拖动一个按钮并插入一个单元格。它适用于以下代码 -

//button1 is initially placed in a view called scrollview
[button1 addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];

[button1 removeTarget:self action:@selector(insertcell) forControlEvents:UIControlEventTouchUpInside];

CGPoint pointfordeterminingrow;

- (IBAction) imageMoved:(UIButton *) sender withEvent:(UIEvent *) event {

    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    UIControl *control = sender;
    control.center = point;

    pointfordeterminingrow=point;   // point where the button is hovering now

    if ([sender state] == UIGestureRecognizerStateBegan) {

        [self.view addSubview:sender];

    }

    if ([sender state] == UIGestureRecognizerStateChanged) {

        [scrollview addSubview:sender];

    }

    if ([sender state] == UIGestureRecognizerStateEnded) {

        [scrollview addSubview:sender];

    }

}

- (int)rowAtPoint:(CGPoint)point {

    NSIndexPath* newIndexPath = [MainTableView indexPathForRowAtPoint:point];
    return newIndexPath == nil ? [items count] : newIndexPath.row;

     //items is a mutable array has the content of each cell
}

-(void)insertcell {

    int row = [self rowAtPoint:pointfordeterminingrow];

    NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:row inSection:0];

    [self insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath                 indexPathForRow:newIndexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

这些代码在 indexpath 上插入一个单元格,在该单元格上方放置按钮 //touchuped 方法被调用。

我的问题是:

我得到的“newIndexPath”是一个数字(表格视图中的行),按钮被放置在该数字上。这种“insertcell”方法在 tableview 不滚动的情况下工作正常,

当 TableView 滚动时,“rowAtPoint”返回一个数字,该数字是 indexpath 处的行,到目前为止是可见的。

换句话说,如果按钮被放在 indexpath 58 上方并且如果上面隐藏了 50 个单元格(通过滚动),我得到数字 8,(不是 58)

因此,当在 indexpath 58 处放置按钮时,会在 INDEXPATH 8 处插入一个单元格。

我需要建议以在某个点在 tableview 中获取 EXACT indexpath。前提是“点”是 self.view 中的 CGPoint。

4

1 回答 1

1

试试这个:

int row = [self rowAtPoint:pointfordeterminingrow];

[myTableView visibleCells];  // call this first to avoid possible iOS bug in next statement
NSArray *visIndexPaths = [myTableView indexPathsForVisibleRows]; 


NSIndexPath* newIndexPath = [visIndexPaths objectAtIndex:row];
于 2012-09-17T07:08:35.160 回答