theDuncs
theDuncs

Reputation: 4843

Create a draggable UIView on long press of a different view

I have implemented something that does the following:

I am showing a full-screen UICollectionView with different items. Underneath this view (out of sight) is a "detail" view for one of the items.

When a user long-presses one of the UICollectionView items, I would like to hide the UICollectionView to reveal the "detail" view behind.

I will then instantiate a new UIView which is hovering over this view and is draggable. The user can then drag and drop this new UIView into position on the "detail" screen.

The only part which I am having trouble with is the syncing of the long-press with the draggable view. I would like the user to long-press on the UICollectionView, and then be immediately dragging the draggable view.

How do I connect these two actions?

At the moment the UICollectionView calls a delegate on the lower view, which instantiates the draggable view:

- (void)contactAlgorithm:(ContactAlgorithmViewController *)contactFlowViewController didLongPressContact:(CDContact *)contact {    
DraggableContactView *draggableView= [[DraggableContactView alloc] initWithContact:contact];
[self.view addSubview:draggableView.view];

}

But how do I make this draggable view the view which is being dragged by the long.press?

enter image description here enter image description here

Upvotes: 2

Views: 1151

Answers (1)

santhu
santhu

Reputation: 4792

First get the frame of the item which was long pressed. Add the draggable view at exactly that frame.

Now, add pan gesture recogniser to that view and set delegate of that gesture to viewController , and whenever move occurs delegate method will be called. There change the frame of draggable view to follow touch.

Instead of adding pan gesture, you can use touchesMoved method of viewController.

CODE:
using below code, you can drag the view without using pan gesture.

//have a class property of DraggableContactView
@implementation ViewController{

    DraggableContactView *dragableView;
}

Selector method of longPressGestureRecogniser

-(void)longPress:(UILongPressGestureRecognizer *)ges{

    if(dragableView==nil){
        dragableView=[[DraggableContactView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        dragableView.backgroundColor =[UIColor greenColor];
        [self.view addSubview:dragableView];
    }
    CGPoint p =[ges locationInView:self.view];
    [dragableView setCenter:p];
}

Upvotes: 3

Related Questions