Last active
May 21, 2022 10:07
-
-
Save gsoykan/4b77614aa827ba3243e0ed9b7e268ad4 to your computer and use it in GitHub Desktop.
ListScrollingProxy update for SwiftUI ScrollView programmatic scrolling
This file contains 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
// | |
// ListScrollingProxy.swift | |
// | |
// Created by gurkan soykan on 20.05.2022. | |
// | |
// source: https://stackoverflow.com/questions/60855852/how-to-scroll-list-programmatically-in-swiftui/60855853#60855853 | |
import Foundation | |
import UIKit | |
class ListScrollingProxy { | |
weak var sampleView: UIView? | |
enum Action { | |
case end | |
case top | |
case horizontalEnd | |
case point(point: CGPoint) | |
} | |
private var scrollView: UIScrollView? | |
func catchScrollView(for view: UIView) { | |
sampleView = view | |
if nil == scrollView { | |
scrollView = view.enclosingScrollView() | |
} | |
} | |
func scrollTo(_ action: Action) { | |
if scrollView == nil { | |
if let sampleView = sampleView { | |
scrollView = sampleView.enclosingScrollView() | |
} | |
} | |
if let scroller = scrollView { | |
var rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1)) | |
switch action { | |
case .end: | |
rect.origin.y = scroller.contentSize.height + | |
scroller.contentInset.bottom + scroller.contentInset.top - 1 | |
case .horizontalEnd: | |
rect.origin.x = scroller.contentSize.width + | |
scroller.contentInset.right + scroller.contentInset.left - 1 | |
case .point(let point): | |
rect.origin.y = point.y | |
default: { | |
// default goes to top | |
}() | |
} | |
scroller.scrollRectToVisible(rect, animated: true) | |
} | |
} | |
} | |
extension UIView { | |
func enclosingScrollView() -> UIScrollView? { | |
var next: UIView? = self | |
repeat { | |
next = next?.superview | |
if let scrollview = next as? UIScrollView { | |
return scrollview | |
} | |
} while next != nil | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment