I've set-up a scrollview with paging enabled. Inside the scrollview is a UIImageView (tutorialImageView) that is linked to the image view on storyboard.
I have an array of images which I want to be shown in the scroll view as pages.
Everything seems to work fine (paging correctly) but only the last image loaded from the array shows. Thus Page 1,2,3 are all blank, and then slide4.png shows as it should on page 4.
import Foundation
import UIKit
class TutorialViewController: UIViewController {
@IBOutlet weak var back: UIButton?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var tutorialImageView: UIImageView?
var slides:[UIImage] = [UIImage(named: "slide1.png")!, UIImage(named: "slide2.png")!, UIImage(named: "slide3.png")!, UIImage(named: "slide4.png")!]
var frame: CGRect = CGRectMake(0, 0, 0, 0)
override func viewDidLoad() {
super.viewDidLoad()
for index in 0..<slides.count {
frame.origin.x = self.scrollView!.frame.size.width * CGFloat(index)
frame.size = self.scrollView!.frame.size
self.scrollView!.pagingEnabled = true
var subView = UIView(frame: frame)
tutorialImageView!.image = slides[index]
subView.addSubview(tutorialImageView!)
self.scrollView!.addSubview(subView)
}
self.scrollView!.contentSize = CGSizeMake(self.scrollView!.frame.size.width * CGFloat(slides.count), self.scrollView!.frame.size.height)
}
I'm struggling to see what I'm missing.
Try this, just sub out some stuff from your code and it should work.
Global variables:
var imageWidth: CGFloat = 310
var imageHeight: CGFloat = 400
var xPosition: CGFloat = 0
var scrollViewContentSize: CGFloat = 0
var myImage: UIImage = //array of UIImage
To create the UIImageViews that goes into your scrollview.
for var index = 0; index < myImages.count; index++ {
var myImage: UIImage = myImages[index]!
var myImageView: UIImageView = UIImageView()
myImageView.image = myImage
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.frame.origin.x = xPosition
myImageView.frame.origin.y = 0
imageScrollView.addSubview(myImageView)
xPosition += imageWidth
scrollViewContentSize += imageWidth
imageScrollView.contentSize = CGSize(width: scrollViewContentSize, height: imageHeight)
}