Monday, 9 January 2017

UIScrollView Programmatically in Swift.

UIScrollView Programmatically Add UIImageView as SubView in Swift.




** Write in ViewController.swift


import UIKit
class ViewController: UIViewController {
   
     @IBOutlet weak var myScrollView: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    
        let myImages=["cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg","cat.jpg"]
        let imageWidth:CGFloat = 275
        let imageHeight:CGFloat = 147
        var yPosition:CGFloat = 0
        var scrollViewContentSize:CGFloat=0;
        for index in 0 ..< myImages.count
        {
            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.
    }
   
}








No comments:

Post a Comment