简体   繁体   中英

Dragging a UITableView

I am using a UIPanGestureRecognizer to allow my UITableView to be dragged around. I have currently set it so that the UITableView cannot be dragged past 0 or half its width. But now, its frame is set to 0 when I try and drag the UITableView back to 0 from an origin of greater than 0. How can I prevent this and allow dragging of the UITableView back to 0? I have tried the following, but I can't quite find out why the outlined code is causing this.

- (void) handlePan:(UIPanGestureRecognizer *) pan {

    CGPoint point = [pan translationInView:_tableView];

    CGRect frame = [_tableView frame];

    if (point.x <= _tableView.frame.size.width / 2) {
        frame.origin.x = point.x;
    }

    NSLog(@"%f : %f", frame.origin.x, _tableView.frame.origin.x);
    //outline begin!
    if (frame.origin.x < 0 && _tableView.frame.origin.x >= 0) {
        frame.origin.x = 0;
    }
    //outline end!
    isFilterViewShowing = frame.origin.x > 0;

    [_tableView setFrame:frame];

}

This is not the prettiest code, but that is working in the simulator.
For this code to work you need to add an instance variable.
This code may not behave exactly as you want it, because it's keeping track of "negative" x position, so you get some "threshold" effect that you may not want depending on you design choice.

- (void) handlePan:(UIPanGestureRecognizer *) pan {

if (pan.state == UIGestureRecognizerStateBegan)
{
    //  cache the starting point of your tableView in an instance variable
    xStarter = _tableView.frame.origin.x;
}

// What is the translation
CGPoint translation = [pan translationInView:self.tableView];
//  Where does it get us
CGFloat newX = xStarter + translation.x;

CGFloat xLimit = self.tableView.superview.bounds.size.width / 2;

if (newX >= 0.0f && newX <= xLimit)
{
    //  newX is good, don't touch it
}
else if (newX < 0)
{
    newX = 0;
}
else if (newX > xLimit)
{
    newX = xLimit;
}

CGRect frame = self.tableView.frame;
frame.origin.x = newX;

[_tableView setFrame:frame];

if (pan.state == UIGestureRecognizerStateEnded)
{
    //  reset your starter cache
    xStarter = 0;
}
}

Have you notice how [pan translationInView:aView]; is returning the offset of the pan gesture and not the position of the finger on the screen.
That is why your code don't work as you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM