超过某个阈值时,使UIPanGestureRecognizer拉伸

时间:2013-06-24 08:22:02

标签: iphone ios objective-c cocoa-touch uikit

我正在尝试实现类似于Mac / iOS网页的实现方式,如果你超过某个阈值,主视图会变得“有弹性”,并根据拉动的速度移动。

不同之处在于,我正在尝试使用UIPanGestureRecognizer为UITableViewCells水平执行此操作。

我有一个handlePan方法:

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    [recognizer setMaximumNumberOfTouches:1];
    CGPoint velocity = [recognizer velocityInView:self];

    int panDelta = ([recognizer locationInView:self].x - [recognizer locationInView:self.superview].x);

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        _originalCenter = self.center;
    }

    if (recognizer.state == UIGestureRecognizerStateChanged) {

        CGPoint translation = [recognizer translationInView:self];

        float xVal = 0;
        if (panDelta <= 38) {
            xVal = _originalCenter.x + translation.x;
        } /*else {


           // this is where I struggle.


            xVal = _originalCenter.x;
        }*/
        self.center = CGPointMake(xVal, _originalCenter.y);

    }

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        CGRect newFrame;
        int xOffset = 0;

        newFrame = CGRectMake(xOffset, self.frame.origin.y,
                                          self.bounds.size.width, self.bounds.size.height);

        [UIView animateWithDuration:0.2 animations:^{
            self.frame = newFrame;
        }];
    }
}

我没有任何特定的算法来创建“弹性”;我所要做的就是让滑动不会像用户的互动一样宽,而且流畅。

想法?

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找一个带水平渐近线的简单函数,表示最大偏移量:

// this is where I struggle.
CGFloat maxOffset = 50.0; // change as you like
CGFloat elementWidth = ?; // fill in the width of your view animated, eg: self.frame.size.width
CGFloat absPannedOffset = fabsf(translation.x);
CGFloat rico = powf(elementWidth, 2) / maxOffset;
CGFloat absOffset = (((- 1 / rico) * powf(absPannedOffset - elementWidth, 2)) + maxOffset);

if (pannedOffset < 0) {
    xVal = -absOffset;
} else {
    xVal = absOffset;
}