UIScrollView Programmatically Add UIImageView as SubView. Example in Swift.

In this video I demonstrate how to programmatically add several images as subviews to UIScrollView in Swift.

In my example I use UIImageView but it can be a custom user interface design ex. XIB file. To learn how to create your own reusable custom user interface files watch this video:
Creating custom user interface files with XIB in Xcode 6 and Swift

Source code:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var myScrollView: UIScrollView!

func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.myScrollView.backgroundColor = UIColor.blackColor()

let myImages=["cat1.jpeg","cat2.jpeg","cat3.jpeg","cat1.jpeg","cat2.jpeg","cat3.jpeg","cat1.jpeg","cat2.jpeg","cat3.jpeg"]

let imageWidth:CGFloat = 275
let imageHeight:CGFloat = 147
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0;

for var index=0; index<myImages.count; index++

let myImage:UIImage = UIImage(named: myImages[index])!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.ScaleAspectFit

myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.center = self.view.center
myImageView.frame.origin.y = yPosition


let spacer:CGFloat = 20

yPosition+=imageHeight + spacer
scrollViewContentSize+=imageHeight + spacer

myScrollView.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)



override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.