Last active
October 10, 2024 04:03
-
-
Save pixeldock/f1c3b2bf0f7fe48d412c09fcb2705bf1 to your computer and use it in GitHub Desktop.
A ViewController with a vertical ScrollView using AutoLayout to position the scrolled subviews
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewControllerWithVerticalScrollView.swift | |
// VerticalScrollViewAL | |
// | |
// Created by Jörn Schoppe on 12.08.18. | |
// Copyright © 2018 Jörn Schoppe. All rights reserved. | |
// | |
import UIKit | |
class ViewControllerWithVerticalScrollView: UIViewController { | |
let scrollView = UIScrollView() | |
let subViews = [UIView(), UIView(), UIView(), UIView()] | |
let colors: [UIColor] = [.green, .blue, .red, .orange] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
var constraints: [NSLayoutConstraint] = [] | |
view.addSubview(scrollView) | |
scrollView.translatesAutoresizingMaskIntoConstraints = false | |
constraints.append(contentsOf: [ | |
scrollView.topAnchor.constraint(equalTo: view.topAnchor), | |
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), | |
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), | |
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor) | |
]) | |
subViews.enumerated().forEach { index, subview in | |
subview.backgroundColor = colors[index] | |
scrollView.addSubview(subview) | |
subview.translatesAutoresizingMaskIntoConstraints = false | |
constraints.append(contentsOf: [ | |
subview.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), | |
subview.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), | |
subview.heightAnchor.constraint(equalToConstant: 400) // only needed in this demo because the subviews are empty | |
]) | |
switch index { | |
case 0: | |
constraints.append(contentsOf: [ | |
subview.topAnchor.constraint(equalTo: scrollView.topAnchor), | |
subview.widthAnchor.constraint(equalTo: scrollView.widthAnchor) | |
]) | |
case subViews.count - 1: | |
constraints.append(contentsOf: [ | |
subview.topAnchor.constraint(equalTo: subViews[index - 1].bottomAnchor), | |
subview.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) | |
]) | |
default: | |
constraints.append(subview.topAnchor.constraint(equalTo: subViews[index - 1].bottomAnchor)) | |
} | |
NSLayoutConstraint.activate(constraints) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment