Swift - viewControllers之间的无限滚动

时间:2015-07-25 13:17:46

标签: ios iphone xcode swift uiscrollview

在我的ViewController中,我有一个包含两个viewControllers(AviewController和BviewController)的UIScrollView。 滚动工作正常但是,我想添加一个无限循环,这意味着当滚动到达最后一个视图(BviewController)时,AviewController应该是下一个,反之亦然。

无法找到实现此方法。任何想法?

到目前为止,我已经在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++;
    }

1 个答案:

答案 0 :(得分:0)

一种覆盖UIScrollView的方法,将内容大小填充到比内容大得多的位置,然后在滚动时覆盖layoutSubviews以重新定位视图。

Apple提供的示例如下:https://developer.apple.com/library/ios/samplecode/StreetScroller/Introduction/Intro.html

特别要查看InfiniteScrollView文件https://developer.apple.com/library/ios/samplecode/StreetScroller/Listings/StreetScroller_InfiniteScrollView_m.html

以及layoutSubviews和recenterIfNecessary方法。