如何重新创建iOS App Store图像幻灯片?

时间:2015-05-28 14:37:24

标签: ios swift uiscrollview

所以我对Swift还很陌生,我想知道是否有人可以帮我重新创建iOS Appstore顶部的图片幻灯片。

是UIImageViews还是CollectionView单元格的滚动视图?

我尝试关注并修改this Ray Wenderlich tutorial,但我得到的结果是laisseàdésirer,如下图所示。

而不是三个图像显示我只有两个没有完全填充scrollView,这让我觉得它可能是自动布局的问题。

非常感谢我能得到的所有帮助。

无论如何,这是我的代码:

var pageImages = [UIImage]()
var pageViews: [UIImageView?] = []
@IBOutlet weak var carousel: UIScrollView!   

override func viewDidLoad() {
            super.viewDidLoad()
    //Setting up the image carousel
    pageImages = [UIImage(named: "featured_1")!, UIImage(named: "featured_2")!, UIImage(named: "featured_3")!]
    for _ in 0..<pageImages.count {
        pageViews.append(nil)
    }
    let pagesScrollViewSize = carousel.frame.size
    carousel.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
        height: pagesScrollViewSize.height)
}

func loadPage(page: Int) {
    if page < 0 || page >= pageImages.count {
        // If it's outside the range of what you have to display, then do nothing
        return
    }

    // 1
    if let pageView = pageViews[page] {
        // Do nothing. The view is already loaded.
    } else {
        // 2
        var frame = carousel.bounds
        frame.origin.x = frame.size.width * CGFloat(page)
        frame.origin.y = 0.0

        // 3
        let imageView = UIImageView(image: pageImages[page])
        imageView.contentMode = .ScaleAspectFit
        imageView.frame = frame
        carousel.addSubview(imageView)

        // 4
        pageViews[page] = imageView
    }
}

func purgePage(page: Int) {
    if page < 0 || page >= pageImages.count {
        // If it's outside the range of what you have to display, then do nothing
        return
    }

    // Remove a page from the scroll view and reset the container array
    if let pageView = pageViews[page] {
        pageView.removeFromSuperview()
        pageViews[page] = nil
    }
}

func loadVisiblePages() {
    // First, determine which page is currently visible
    let pageWidth = carousel.frame.size.width
    let page = Int(floor((carousel.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))

    // Work out which pages you want to load
    let firstPage = page - 1
    let lastPage = page + 1

    // Purge anything before the first page
    for var index = 0; index < firstPage; ++index {
        purgePage(index)
    }

    // Load pages in our range
    for index in firstPage...lastPage {
        loadPage(index)
    }

    // Purge anything after the last page
    for var index = lastPage+1; index < pageImages.count; ++index {
        purgePage(index)
    }
}

override func scrollViewDidScroll(scrollView: UIScrollView) {
    loadVisiblePages()
    }
}

The image views do not completely fill the scroll view and only two images appear even after scrolling

0 个答案:

没有答案