General Middleware

Implement ScrollView in Swift Xcode

Below code will layout 3 images in a scrollview. The basic steps are:

  1. Create a UIScrollView with a designated frame
  2. Add the UIScrollView to the view
  3. Create three UIImageView Objects with the desired frame size
  4. Add all those UIImageView into the UIScrollView object
  5. Define the contentSize of the UIScrollView. It will define the total length (including the on screen and the off screen) of the UIScrollView.

Note : You need to designed the start coordinate of the Y-Axis for each UIImageView, so that there is no overlapping.

//
//  ViewController.swift
//  How to create ScrollView
//
//  Created by Animesh Banerjee on 30/4/21.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .red
        let scrollView = UIScrollView(frame: CGRect(x: 10, y: 10, width: view.frame.size.width - 20, height: view.frame.size.height - 20))
        scrollView.backgroundColor = .green
        view.addSubview(scrollView)
        
//In the below code, you need to replace the image names with that of yours
        let imageView1 = UIImageView(image: UIImage(named: "team1"))
        imageView1.sizeToFit()
        imageView1.frame = CGRect(x: 10, y: 10, width: Int(view.frame.size.width), height: 300)
        
        let imageView2 = UIImageView(image: UIImage(named: "team2"))
        imageView2.sizeToFit()
        imageView2.frame = CGRect(x: 10, y: 320, width: Int(view.frame.size.width), height: 300)
        
        let imageView3 = UIImageView(image: UIImage(named: "team3"))
        imageView3.sizeToFit()
        imageView3.frame = CGRect(x: 10, y: 640, width: Int(view.frame.size.width), height: 300)
        
        scrollView.addSubview(imageView1)
        scrollView.addSubview(imageView2)
        scrollView.addSubview(imageView3)
        
        scrollView.contentSize = CGSize(width: view.frame.size.width, height: 3000)
    }
    
}

Leave a Reply

Your email address will not be published. Required fields are marked *