Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created October 18, 2023 09:09
Show Gist options
  • Save terrysahaidak/a7d625b67a29d32bdffde46d4218aaf7 to your computer and use it in GitHub Desktop.
Save terrysahaidak/a7d625b67a29d32bdffde46d4218aaf7 to your computer and use it in GitHub Desktop.
Insert Space To Scroll View on Drag end
//
// ViewController.swift
// ScrollViewInsertTest
//
// Created by Terry Sahaidak on 18.10.2023.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView()
let stackView = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
setupScrollViewWithStackView()
scrollView.delegate = self
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if (scrollView.contentOffset.y < -100) {
scrollView.bounces = false
let myEmptyView = UIView()
myEmptyView.heightAnchor.constraint(equalToConstant: scrollView.contentOffset.y * -1 - 60).isActive = true
myEmptyView.backgroundColor = .white
stackView.insertArrangedSubview(myEmptyView, at: 0)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.bounces = true
}
func setupScrollViewWithStackView() {
scrollView.frame = view.bounds
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(scrollView)
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10 // adjust this value for spacing between text views
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
setupTextViews(in: stackView)
}
func setupTextViews(in stackView: UIStackView) {
for i in 1...20 {
let textView = UITextView()
textView.text = "Item \(i)"
textView.heightAnchor.constraint(equalToConstant: 40).isActive = true
stackView.addArrangedSubview(textView)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment