拖动UITableView

时间:2011-12-04 22:00:24

标签: objective-c ios uitableview frame uigesturerecognizer

我使用UIPanGestureRecognizer允许我的UITableView被拖动。我目前已将其设置为UITableView无法拖过0或其宽度的一半。但是现在,当我尝试将UITableView从大于0的原点拖回0时,它的帧被设置为0.如何防止这种情况并允许将UITableView拖回0?我已经尝试了以下内容,但我不能完全找出为什么概述的代码导致了这一点。

- (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];

}

1 个答案:

答案 0 :(得分:0)

这不是最漂亮的代码,但是在模拟器中工作 要使此代码起作用,您需要添加一个实例变量 此代码的行为可能与您想要的完全无关,因为它会跟踪“负”x位置,因此您可能会获得某些“阈值”效果,根据您的设计选择,您可能不需要这些效果。

- (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;
}
}

您是否注意到[pan translationInView:aView];如何返回pan gesture的偏移而不是手指在屏幕上的位置。
这就是为什么你的代码不能按预期工作的原因。