2011-12-04 30 views
0

我正在使用UIPanGestureRecognizer来允许我的UITableView被拖动。我目前已将其设置为使UITableView不能拖过0或其一半宽度。但现在,当我尝试从大于0的原点将UITableView拖回到0时,它的帧被设置为0.我怎样才能防止这种情况,并允许将UITableView拖回0?我已经尝试了以下内容,但我无法完全弄清楚为什么轮廓代码导致这种情况。拖动UITableView

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

} 

回答

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,而不是屏幕上的手指的位置偏移。
这就是您的代码无法按预期工作的原因。

+0

这实际上没有帮助,我尝试使用superView,但没有找到触摸。你能理解为什么我的代码不工作吗? –

+0

不要在你的superView中寻找触摸,让pan在superView的坐标系中返回翻译CGPoint。 –

+0

你能举个例子吗? –

相关问题