1

I would like to know how to create a horizontal scrollview in swift programmatically without using storyboards, with a page controller.

  • [check this](https://stackoverflow.com/a/44933358/1066828) & [this](http://geekyviney.blogspot.com/2015/03/adding-scroll-views-programmatically.html) – Fahim Parkar Mar 28 '18 at 05:07

2 Answers2

1
import UIKit

class SecondViewController: UIViewController, UIScrollViewDelegate {

    var scrollview = UIScrollView()
    var imageview = UIImageView()
    var view1 = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        imageview.frame = CGRect(x: 0, y: 0, width: view.frame.size.width , height: 1000)
         imageview.image = UIImage(named: "image")
        scrollview.delegate = self
        scrollview.contentSize = CGSize(width: imageview.frame.width, height: imageview.frame.height)


        scrollview.backgroundColor = UIColor.red
        imageview.backgroundColor =  UIColor.green

        self.scrollview.addSubview(imageview)
        view.addSubview(scrollview)
        scrollview.translatesAutoresizingMaskIntoConstraints = false



        scrollview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        scrollview.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        scrollview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true


        // Do any additional setup after loading the view.
    }
Srinivasan_iOS
  • 972
  • 10
  • 12
0

Try This

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView: UIScrollView!

    let textData: String = "Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class."

    override func viewDidLoad() {
        super.viewDidLoad()

        let textLable = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 200))
        textLable.text = textData

        self.scrollView = UIScrollView()
        self.scrollView.delegate = self
        self.scrollView.contentSize = CGSize(width: textLable.frame.width, height: textLable.frame.height)

        scrollView.addSubview(textLable)
        view.addSubview(scrollView)

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        scrollView.frame = view.bounds
    }

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


}
Sabbir Ahmed
  • 351
  • 1
  • 13