Search code examples
iosswiftuiscrollviewuiimageviewscroll-paging

UIImageViews not scaling correctly in UIScrollView with paging


I'm trying to build a very simple UIScrollView with several images where paging is enabled.

However, I can't seen to get the images to correctly be resized to the bounds of my UIScrollView. The images are always bigger than the bounds, thus messing with my paging.

I have a UIScollView and a UIPageControl in Interface Builder and link it in my ViewController swift file.

Here is my viewDidLoad method (pageImages is defined as var pageImages: [UIImage] = [] and pageViews as var pageViews: [UIImageView?] = []:

override func viewDidLoad() {
    scrollView.delegate = self
    scrollView.pagingEnabled = true
    scrollView.scrollEnabled = true
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.showsVerticalScrollIndicator = false
    scrollView.bounces = true
    scrollView.scrollsToTop = false

    pageImages = [UIImage(named: "image1")!,
        UIImage(named: "image2")!,
        UIImage(named: "image3")!,
        UIImage(named: "image4")!,
        UIImage(named: "image5")!]

    let pageCount = pageImages.count

    pageControl.currentPage = 0
    pageControl.numberOfPages = pageCount

    for (var i=0; i<pageCount; i++) {
        var xOrigin: CGFloat = CGFloat(i) * scrollView.bounds.size.width

        let imageView: UIImageView = UIImageView(frame: CGRectMake(xOrigin, 0, scrollView.bounds.size.width, scrollView.bounds.size.height))
        imageView.image = pageImages[i]
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        scrollView.addSubview(imageView)
    }


    let pagesScrollViewSize = scrollView.frame.size
    scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
        height: pagesScrollViewSize.height)
}

My scrollViewDidScroll method is as follows:

func scrollViewDidScroll(scrollView: UIScrollView) {
    let pageWidth = self.scrollView.frame.size.width
    let page = Int(floor((self.scrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1)
    self.pageControl.currentPage = page
}

Can anyone spot my mistake? Do I have to set the contentMode maybe in viewWillAppear or viewDidAppear?


Solution

  • Try setting up your imageViews sizes under:

    • (void)viewDidLayoutSubviews

    At this point, autolayout had finished resizing your views/subviews according to the layout system you defined on interface builder so if your calculations are correct (according your requirements) this should work out fine.