In my ipad app I need to drag and drop a UIButton to insert a cell. I managed to drag a button and inserting a cell by touchupinside event. It works with following code –
//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];
}
These codes insert a cell at the indexpath above which the button is dropped //touchuped method gets called.
MY PROBLEM IS:
“newIndexPath” which I get is a number (row in tableview) on which the button is dropped. This “insertcell” method works fine in situation when the tableview is not scrolled,
When the TableView is scrolled “rowAtPoint” returns a number which is the row at indexpath witch is VISIBLE as of now.
In Other Words, if the button is dropped above indexpath 58 and if 50 cells are hidden above (by scrolling) i get the number 8,(not 58)
So when the button is dropped at indexpath 58 a cell is inserted AT INDEXPATH 8.
I need suggestions to get the EXACT indexpath in a tableview at a point. provided the “point” is the CGPoint in self.view.
Try this: