106 lines
2.7 KiB
Swift
106 lines
2.7 KiB
Swift
//
|
|
// AutoScrollView.swift
|
|
// OnCue
|
|
//
|
|
// Created by Pradyun Setti on 23/06/2024.
|
|
//
|
|
|
|
import SwiftUI
|
|
import SwiftData
|
|
|
|
//struct AutoScrollView<Content: View>: View {
|
|
// let content: Content
|
|
// var scrollSpeed: Double = 15.0
|
|
//
|
|
// @State private var offset: Double = 0.0
|
|
//
|
|
// init(scrollSpeed: Double = 0, @ViewBuilder _ content: () -> Content) {
|
|
// self.content = content()
|
|
// self.scrollSpeed = scrollSpeed
|
|
// }
|
|
//
|
|
// var body: some View {
|
|
// ScrollView {
|
|
// content
|
|
// .offset(y: offset)
|
|
// }
|
|
// }
|
|
//
|
|
// func startScrolling() {
|
|
//
|
|
// }
|
|
//
|
|
// func stopScrolling() {
|
|
//
|
|
// }
|
|
//
|
|
// mutating func setScrollSpeed(_ speed: Double) {
|
|
// self.scrollSpeed = speed
|
|
// }
|
|
//}
|
|
|
|
struct AutoScrollView<Content: View>: View {
|
|
@State private var scrollOffset: CGFloat = 0
|
|
@State private var timer: Timer? = nil
|
|
|
|
let content: Content
|
|
var scrollSpeed: CGFloat // Adjust this value to control the scroll speed
|
|
|
|
init(scrollSpeed: Double = 1.0, @ViewBuilder _ content: () -> Content) {
|
|
self.content = content()
|
|
self.scrollSpeed = scrollSpeed
|
|
}
|
|
|
|
var body: some View {
|
|
ScrollViewReader { proxy in
|
|
ScrollView {
|
|
content
|
|
.id(0) // Assign an ID to the content
|
|
.background(GeometryReader { geo in
|
|
Color.clear.onAppear {
|
|
let contentHeight = geo.size.height
|
|
startTimer(proxy: proxy, contentHeight: contentHeight)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
.onDisappear {
|
|
stopTimer()
|
|
}
|
|
}
|
|
|
|
private func startTimer(proxy: ScrollViewProxy, contentHeight: CGFloat) {
|
|
timer?.invalidate() // Invalidate any existing timer
|
|
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { _ in
|
|
withAnimation {
|
|
scrollOffset += scrollSpeed
|
|
proxy.scrollTo(0, anchor: .bottom)
|
|
proxy.scrollTo(scrollOffset, anchor: .bottom)
|
|
}
|
|
|
|
// Reset scroll offset when it reaches the end
|
|
if scrollOffset >= contentHeight {
|
|
stopTimer()
|
|
}
|
|
}
|
|
}
|
|
|
|
private func stopTimer() {
|
|
timer?.invalidate()
|
|
timer = nil
|
|
}
|
|
}
|
|
|
|
#Preview {
|
|
let config = ModelConfiguration(isStoredInMemoryOnly: true)
|
|
let container = try! ModelContainer(for: OCProject.self, configurations: config)
|
|
|
|
container.mainContext.insert(PreviewData.project)
|
|
|
|
return AutoScrollView {
|
|
Text(PreviewData.project.script)
|
|
.font(.system(size: 45))
|
|
.padding(.horizontal)
|
|
}
|
|
}
|