Pages

Adding Scroll Views programmatically

Scroll View are one of the very basic feature that you are interacting with usually with your smartphone.You are using it in your browser to view images, in gallery as well to view images && even in your contact app to scroll && view your contacts etc. The very basic concept that you should need to know about Scroll Views is their content size which is of CGSize type that specifies the width && height of the contents, because of this property of scroll views gets to know about the size of the contents that it will be displaying. Scroll view is subclass of type UIView && you will add your view to scroll view by using method addSubview() method. One more thing about content size you need to consider is that your content size should set properly or else contents will not scroll.
Consider an example in which we add an image to the image view && then we will add this view to the scroll view so that we will be able to scroll it. Here is the piece of code && place into the ViewController.Swift file. 
class ViewController: UIViewController {
            //instantiating an object of image view.
    var imageView: UIImageView!
            //instantiating an object of scroll view.
    var scrollView: UIScrollView!
            //creating an object && assigning an image named "shanks"
    var image = UIImage(named: "shanks")

    override func viewDidLoad() {
        super.viewDidLoad()
                //setting image to the image view
        imageView = UIImageView(image: image)
                //setting the frame of the scroll view.
        scrollView = UIScrollView(frame: view.bounds)
                //adding imageview as a subview of scroll view
        scrollView.addSubview(imageView)
                // content size of the scroll view is the size of the image
        scrollView.contentSize = imageView.bounds.size
                //scroll view is the subview of main view
        view.addSubview(scrollView)
    }    
}

Outside the viewDidLoad() method we are only creating the objects of image view && scroll view. In the viewDidLoad() method we are setting the image to the image view which is done by line of code..
                  "imageView = UIImageView(image: image)"
After then we are setting the size of the scroll view as the size of the main view(screen size) && then set the image view as subview of the scroll view with lines of code...
                   "scrollView = UIScrollView(frame: view.bounds)"
                   "scrollView.addSubview(imageView)"
In the end we are setting the content size of the scroll view so that the image as the content of the scroll view will be scrolled easily. In the end we are just adding the scroll view as the subview of the main view. As output you will be able to see the image on the image view && you will be able to scroll it easily.

No comments:

Post a Comment