jump to current chapter in horizontal view

This commit is contained in:
Toni Förster 2024-05-11 23:24:17 +02:00
parent 7c50db426f
commit ebc48fde90
No known key found for this signature in database
GPG Key ID: 292F3E5086C83FC7
2 changed files with 22 additions and 3 deletions

View File

@ -12,7 +12,10 @@ import SwiftUI
var showThumbnail: Bool
var isCurrentChapter: Bool {
player.currentChapterIndex == chapterIndex
if let currentChapterIndex = player.currentChapterIndex {
return currentChapterIndex == chapterIndex
}
return false
}
var body: some View {

View File

@ -27,7 +27,22 @@ struct ChaptersView: View {
.listStyle(.plain)
#else
ScrollView(.horizontal) {
LazyHStack(spacing: 20) { chapterViews(for: chapters[...]) }.padding(.horizontal, 15)
ScrollViewReader { scrollViewProxy in
LazyHStack(spacing: 20) {
chapterViews(for: chapters[...], scrollViewProxy: scrollViewProxy)
}
.padding(.horizontal, 15)
.onAppear {
if let currentChapterIndex = player.currentChapterIndex {
scrollViewProxy.scrollTo(currentChapterIndex, anchor: .center)
}
}
.onChange(of: player.currentChapterIndex) { currentChapterIndex in
if let index = currentChapterIndex {
scrollViewProxy.scrollTo(index, anchor: .center)
}
}
}
}
#endif
} else if expand {
@ -65,10 +80,11 @@ struct ChaptersView: View {
}
#if !os(tvOS)
private func chapterViews(for chaptersToShow: ArraySlice<Chapter>, opacity: Double = 1.0, clickable: Bool = true) -> some View {
private func chapterViews(for chaptersToShow: ArraySlice<Chapter>, opacity: Double = 1.0, clickable: Bool = true, scrollViewProxy: ScrollViewProxy? = nil) -> some View {
ForEach(Array(chaptersToShow.indices), id: \.self) { index in
let chapter = chaptersToShow[index]
ChapterView(chapter: chapter, chapterIndex: index, showThumbnail: showThumbnails)
.id(index)
.opacity(index == 0 ? 1.0 : opacity)
.allowsHitTesting(clickable)
}