简体   繁体   中英

Swift - infinite scroll between viewControllers

In my ViewController I have a UIScrollView that contains two viewControllers (AviewController and BviewController). The scrolling works fine however, I would like to add an infinite loop to it means that when the scroll reaches the last view ( BviewController ) AviewController should be next and vice-versa.

Cannot find the way to implement this. Any Ideas?

So far I have in viewDidLoad:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let AviewController = storyboard.instantiateViewControllerWithIdentifier("A_id") as! AviewController;
    let BviewController = storyboard.instantiateViewControllerWithIdentifier("B_id") as! BviewController;

    scrollView!.contentSize = CGSizeMake(2*CGRectGetWidth(AviewController.view.frame), CGRectGetHeight(view.frame));

    let viewControllers = [AviewController, BviewController]

    var idx:Int = 0;

    for viewController in viewControllers {
        // index is the index within the array
        // participant is the real object contained in the array
        addChildViewController(viewController);
        let originX:CGFloat = CGFloat(idx) * CGRectGetWidth(scrollView!.frame);
        viewController.view.frame = CGRectMake(originX, 0, viewController.view.frame.size.width, viewController.view.frame.size.height);
        scrollView!.addSubview(viewController.view)
        viewController.didMoveToParentViewController(self)
        idx++;
    }

One way to override UIScrollView, pad the content size to much larger than your content, then override layoutSubviews to re-position views as you scroll.

An example provided by Apple is here: https://developer.apple.com/library/ios/samplecode/StreetScroller/Introduction/Intro.html

In particular look at the InfiniteScrollView file https://developer.apple.com/library/ios/samplecode/StreetScroller/Listings/StreetScroller_InfiniteScrollView_m.html

And the layoutSubviews and recenterIfNecessary methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM