平滑我的滚动TouchesMoved

时间:2015-07-05 01:29:46

标签: ios objective-c

我有一个位于桌面视图上方的半透明视图。当我将视图拖到靠近屏幕底部时,我想平滑地滚动它下面的表视图。

我想模仿:

用户拖动屏幕底部附近的悬停视图并将其保留在那里。 表视图滚动直到它们放开或直到它们到达表的底部。 用户可以离开悬停视图。

目前我在做:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (!_hoverViewTouch) {
        return;
    }

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGPoint prevLocation = [touch previousLocationInView:self];

    //scroll down.
    if (prevLocation.y < location.y) {
        if (location.y >= _table.frame.size.height - rowHeight) {
            NSArray *cells = [_table visibleCells];
            UITableViewCell *cell = [cells objectAtIndex:round(cells.count / 2)];
            NSIndexPath *indexPath = [_table indexPathForCell:cell];
            [_table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:true];
        }
    }

    CGRect frame = [hoverView frame];
    frame.origin.y = location.y - (hoverView.frame.size.height / 2.0f);
    [hoverView setFrame:frame];
}

然而,它滚动得如此之快到桌子的底部。如何减慢速度或平滑滚动?

1 个答案:

答案 0 :(得分:3)

UITableView的scrollToRowAtIndexPath方法无法控制动画速度。相反,您可以使用CADisplayLink顺畅更新表格视图contentOffset

- (void)startAnimatingTable
{
    self.scrollStartDate = [NSDate date];
    self.startContentOffset = self.tableView.contentOffset;
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkFired:)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)stopAnimatingTable
{
    [self.displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.displayLink = nil;
}

- (void)displayLinkFired:(CADisplayLink *)displayLink
{
    NSTimeInterval interval = -[self.scrollStartDate timeIntervalSinceNow];
    CGFloat speed = 100;
    CGFloat yOffset = self.startContentOffset.y + speed * interval;
    self.tableView.contentOffset = CGPointMake(self.startContentOffset.x, yOffset);
}