4

I have a UIScrollView which is the same width as its superview. It has a very wide contentSize and scrolls horizontally.

I am trying to use the delegate method scrollViewWillEndDragging:withVelocity:targetContentOffset: to set targetContentOffset->x to a negative value (i.e. move the left edge of the content area closer to the center of the screen).

Setting the value seems to work (NSLog shows a change before and after) but the scrollview seems to ignore the modified targetContentOffset and just ends scrolling at 0.

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    NSLog(@"target: %@", NSStringFromCGPoint(*targetContentOffset));
    if (targetContentOffset->x <= 0.0)
    {
        targetContentOffset->x = -300;
    }

    NSLog(@"target: %@", NSStringFromCGPoint(*targetContentOffset));
}

Does anybody know if this can be done using this method or should I be doing it some other way?

Killian
  • 414
  • 2
  • 10

1 Answers1

0

I've managed to solve the similar problem by manipulating with contentInset property.

Here is the example in Swift:

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    // Determine threshold for dragging to freeze content at the certain position
    if scrollView.contentOffset.y < -50 {
        // Save current drag offset to make smooth animation lately
        var offsetY = scrollView.contentOffset.y
        // Set top inset for the content to freeze at
        scrollView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
        // Set total content offset to preserved value after dragging
        scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: false)
        // Make any async function you needed to
        yourAsyncMethod(complete: {() -> Void in
            // Set final top inset to zero
            self.tripsTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
            // Set total content offset to initial position
            self.tripsTableView.setContentOffset(CGPoint(x: 0, y: -50), animated: false)
            // Animate content offset to zero
            self.tripsTableView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        })
    }
}

You can improve it to use for horizontal scroll

Xavier Lowmiller
  • 1,381
  • 1
  • 15
  • 24
Dmytro Babych
  • 270
  • 2
  • 7