I'm using a UIScrollView as the basis of a component that makes use of core animation. When the user swipes the view I would like to position elements according to the destination (resting) position of the scroll view. For this, I need to calculate the destination contentOffset of the UIScrollView in the scrollViewWillBeginD开发者_运维百科ecelerating: method or similar.
The reason I need this is that I'll be using the destination contentOffset to animate views nested within the scrollview's contentView to their final position. I could of course set up an observer on the contentOffset or similar, but this would result in chaotic animation as the nested views would then update their positions multiple times during deceleration. I'd like this to happen just the once.
Is there a simple way to do this?
There's a delegate method for this:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS5(5_0);
According to the doc:
Called on finger up if the user dragged. velocity is in points/second. targetContentOffset may be changed to adjust where the scroll view comes to rest. not called when pagingEnabled is YES
Not sure if you still need this. but this is how you can get in the delegate of UIScrollView.
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
NSLog(@"X offset: %f", targetContentOffset->x);
NSLog(@"Y offset: %f", targetContentOffset->y);
}
Is there a specific reason why you need to know in advance where the scroll view is going to stop? You could position your views in either layoutSubviews
(if you subclass UIScrollView) or in scrollViewDidScroll:
in the scroll view delegate's implementation.
I believe you are referring to the behavior automatically provided by pagingEnabled
on UIScrollView
. From the iOS Reference Library on UIScrollView
, when paging is enabled, "the scroll view stops on multiples of the scroll view's bounds when the user scrolls." I use this behavior all the time, and I believe is what you are describing. It handles all of the hard work for you - just by setting one property!
UPDATE: I think I misunderstood your question. You can always check the contentOffset
property of the UIScrollView
to determine its current origin within the scroll view. You can do that in one of the delegate methods, probably scrollViewDidEndDecelerating:
.
精彩评论