Objective-C : UIScrollView manual paging

2019-04-15 09:49发布

问题:

I want to use the scrollview as something like a picker in horizontal mode. The scrollview holds up to seven subviews. Each subview represents a value. Always three views are visible and the one in the middle is the selected one.

Scrollview visible at start:

__ | V1 | V2

Scrollview set to view/value two:

V1 | V2 | V3

Scrollview set to last value:

V2 | V3 | __

The real problem I have got is the "pagingEnabled" flag. If pagingEnabled is set to YES the scrollview pages always three subviews/values instead of only one. If pagingEnabled is set to NO the scrollview does not clinch.

Is there a nice solution for my problem?

Thanks a lot, Dan ;)

回答1:

Change the frame of the scrollview to be as if it were only displaying the middle view (i.e. a third of its original width, and offset by the same amount), but then set its clipsToBounds property to NO.



回答2:

I found a solution if anyone else is interested.

Assign you view the delegate of a scrollview. Ovveride scrollViewDidEndDecelerating, afterwards get your current index(page you want) by doing something like.

 NSNumber* currentIndex = [NSNumber numberWithInt:round(scrollview.Contentoffset.x / PAGE_SIZE)];

//Then just update your scrollviews offset with


[scrollview setContentOffset:CGPointMake([currentIndex intValue] * PAGE_SIZE, 0) animated:YES];


回答3:

Since iOS 5, there's the scrollViewWillEndDragging:withVelocity:targetContentOffset: delegate method on UIScrollViewDelegate. This allows you to implement arbitrary paging.

For this to work, you first need to set the pagingEnabled property to NO, otherwise the delegate method I'm talking about isn't called. The scroll view now calls this delegate method whenever the user lifts his finger and the scroll view wants to determine where to finish the scrolling.

The magic is the last argument, targetContentOffset: it's a pointer to a CGPoint and used as a in/out variable. This means this variable tells you where the scrollview wants to scroll to. But it allows you modify this target location. The velocity might also be of interest, it can give you an indication whether the user "pushed" the scroll view or moved it, stopped, then lifted his finger.

For example, here's an implementation that rounds the target x location to the nearest multiple of 100, thus making "pages" of 100 points width.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    targetContentOffset->x = round(targetContentOffset->x / 100.0) * 100.0;
}