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! override func viewDidLoad() { super.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 myScrollView.addSubview(myImageView) let spacer:CGFloat = 20 yPosition+=imageHeight + spacer scrollViewContentSize+=imageHeight + spacer myScrollView.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
I hope that this short Swift programming tutorial was helpful for you. There is some much more to learn about mobile apps development with Swift for iOS platform! Check the video courses below and may be one of them will be just what you need.