8.1. Creating the View of the Screen

Let's declare the UI elements:

//
//  ScrollScreenView.swift
//  App8_scroller
//
//  Created by Sakib Miazi on 5/24/23.
//

import UIKit

class ScrollScreenView: UIView {
    var contentWrapper:UIScrollView!
    var largeImageView:UIImageView!
    var textField1:UITextField!
    var textField2:UITextField!
    var textField3:UITextField!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        
        setupContentWrapper()
        setupLargeImageView()
        setuptextField1()
        setuptextField2()
        setuptextField3()
        
        initConstraints()
    }
    
    //MARK: unused...
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

If you noticed, I have declared a variable called contentWrapper of type UIScrollView. We will wrap the elements we want to include in the scrollable part of the screen.

We also need a large image. I used the following image to load inside the screen:

So, let's import the image into the project:

Let's initialize the UI elements:

As you can see in the image view, I set the image when I initialize it. I also set the content mode to scale aspect fit; and set the clips to bounds to true so that the image view clips the image outside the image view.

Constraints:

ImageView constraints: We should always set the height and weight using constraints for the image view. The height should be a constant; otherwise, it might ruin your layout.

ScrollView constraints: Here, we need to be careful when setting constraints of the scroll view. There are four constraints we must set for the scroll view:

  • topAnchor: set it where the scrollable view starts (top edge of the safe area in this case).

  • leadingAnchor: the left edge of the scrollable view (leading edge of the safe area here).

  • widthAnchor: it is very important to set the width of the ScrollView; otherwise scroll view may behave in uncanny ways.

  • heightAnchor: also, it is absolutely necessary to set the height; otherwise, it might not even scroll. It might become tricky where we have UI elements outside the scroller.

The most important constraints that you must set correctly are: the topAnchor of the topmost UI element and the bottomAnchor of the bottom element.

  • The topAnchor of the topmost element should be set to the topAnchor of the scroll view.

  • The bottomAnchor of the bottom element should be set to the bottomAnchor of the scroll view.

  • Please note the scroll view wraps the elements. So, it is important that you use these anchors of the UI elements the scroll view is wrapping.

Now we need to patch the screen to the controller.

Last updated

Was this helpful?