From 6e964a251b097792f256f5b5e8c783360305e00d Mon Sep 17 00:00:00 2001 From: Mercen Date: Thu, 4 Apr 2024 20:15:59 +0900 Subject: [PATCH] fix: Fix unable Scroll to Top --- .../DDS/Component/ScrollView/ScrollView.swift | 3 ++- Source/DDS/Component/TabView/TabView.swift | 6 +++++- .../TabView/TabViewIdxEnvironment.swift | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 Source/DDS/Component/TabView/TabViewIdxEnvironment.swift diff --git a/Source/DDS/Component/ScrollView/ScrollView.swift b/Source/DDS/Component/ScrollView/ScrollView.swift index f228f02..3ade33f 100644 --- a/Source/DDS/Component/ScrollView/ScrollView.swift +++ b/Source/DDS/Component/ScrollView/ScrollView.swift @@ -37,6 +37,7 @@ public struct DodamScrollView: DodamNavigationViewProtocol { ) } + @Environment(\.tabViewIdx) var tabViewIdx: Int? @State private var topInset: CGFloat! @State private var blueOpacity: CGFloat = 0 @@ -60,7 +61,7 @@ public struct DodamScrollView: DodamNavigationViewProtocol { } } ) - .id(-1) + .id("ScrollToTop-\(tabViewIdx ?? -1)") } .mask(alignment: .bottom) { VStack(spacing: 0) { diff --git a/Source/DDS/Component/TabView/TabView.swift b/Source/DDS/Component/TabView/TabView.swift index 6a71332..e876c20 100644 --- a/Source/DDS/Component/TabView/TabView.swift +++ b/Source/DDS/Component/TabView/TabView.swift @@ -34,6 +34,7 @@ public struct DodamTabView: View { ForEach(contents.indices, id: \.self) { idx in if loadedViews.contains(idx) { contents[idx].content + .environment(\.tabViewIdx, idx) .opacity(selected == idx ? 1 : 0) } } @@ -54,7 +55,10 @@ public struct DodamTabView: View { selected = idx } else { withAnimation(.spring) { - scrollViewProxy.scrollTo(-1, anchor: .top) + scrollViewProxy.scrollTo( + "ScrollToTop-\(idx)", + anchor: .top + ) } } } label: { diff --git a/Source/DDS/Component/TabView/TabViewIdxEnvironment.swift b/Source/DDS/Component/TabView/TabViewIdxEnvironment.swift new file mode 100644 index 0000000..6d620e3 --- /dev/null +++ b/Source/DDS/Component/TabView/TabViewIdxEnvironment.swift @@ -0,0 +1,18 @@ +import SwiftUI + +@available(macOS 12, iOS 15, *) +private struct TabViewIdxEnvironmentKey: EnvironmentKey { + + static var defaultValue: Int? +} + +@available(macOS 12, iOS 15, *) +public extension EnvironmentValues { + + var tabViewIdx: Int? { + get { self [TabViewIdxEnvironmentKey.self] } + set { + self [TabViewIdxEnvironmentKey.self] = newValue + } + } +}