ICoder
ICoder

Reputation: 1347

How can we move a view vertically upward and downwards?

I have a tableview in my main view, and I need to move this tableview vertically with touch.

I want to drag this tableview upwards and downwards when touching at any position, and when my finger moves upward or downward the tableview will move according to the touch.

I have lots of controllers in my main view, so i want to touch the tableview only.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

How do I use these delegates in the question above?

Thanks in advance.

Upvotes: 0

Views: 595

Answers (2)

HarshIT
HarshIT

Reputation: 4915

YOu just make a class , inherited from UITableview

Make a class Drag

Drag.h should be like this

@interface Drag : UITableView { 
    CGPoint touchingPoint;
}

and Modify Drag.m File by including following methods

Drag.m

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{ 
    CGPoint pt = [[touches anyObject] locationInView:self];
    touchingPoint = pt;
    [[self superview] bringSubviewToFront:self];    
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{       
    CGPoint pt = [[touches anyObject] locationInView:self];     
    [UITableView beginAnimations:nil context:nil];
    [UITableView setAnimationDuration:0.1];             
    CGRect newFrame = self.frame;
    newFrame.origin.y += pt.y - touchingPoint.y;    
    [self setFrame:newFrame];   
    [UITableView commitAnimations];     
}

That's it.

Moreover , in Your viewDidLoad method,

put these lines

Drag *objDrag = [[Drag alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];

objDrag.delegate = self;
objDrag.dataSource = self;
[objDrag setUserInteractionEnabled:YES];    

[self.view  addSubview:objDrag];

Remember: for dragging vertically , you must touch the separators of table otherwise it will consider touch to cell and will scroll instead of dragging.

Upvotes: 4

Anil Kothari
Anil Kothari

Reputation: 7733

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event can be used to create table with tapping the view and getting the CGPoint of the view and after then setting the tableview frame with these coordinates.

Note:- It will be better to represent in User Interface if table drag is done with
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; with this function.

Upvotes: 0

Related Questions