Sunday, June 23, 2024
HomeiOS Developmentios - SwiftUI ScrollViewReader scrollTo would not scroll all the way in...

ios – SwiftUI ScrollViewReader scrollTo would not scroll all the way in which to high


I need the ScrollView to scroll to high after I faucet on the tab. It really works however it stops parallel to the navigation title and would not scroll all the way in which under the title as anticipated.

The present behaviour is,

1st faucet: scrolls parallel to the navigation title (Picture 1)
faucet once more: scrolls under nav title as anticipated (Picture 2)

It is a poc of a a lot bigger code so utilizing a ListView isn’t an possibility.

1st Tap
2nd Tap

struct Tabs {
    static let One = "1"
    static let Two = "2"
    static let Three = "3"
}

struct ContentView: View {
  @State var scrollToTop = false
  @State non-public var currentTab: String = Tabs.One
  var physique: some View {
      TabView(choice: tabSelection) {
        TestView(scrollToTop: $scrollToTop)
          .tabItem {
            Label("First", systemImage: "1.circle")
          }.tag(Tabs.One)
      }
  }

  var tabSelection: Binding<String> {
    Binding( get: {
      currentTab
    }, set: { newValue in
      /// Tapped on the identical tab.
      if newValue  == currentTab {
        swap newValue {
        case Tabs.One:
          scrollToTop = true
        case Tabs.Two:
          print(newValue)
        case Tabs.Three:
          print(newValue)
        default:
          return
        }
      }
      currentTab = newValue
    })
  }
}

struct TestView: View {
  @Binding var scrollToTop: Bool
  var physique: some View {
    NavigationView {
      ScrollView {
        ScrollViewReader { proxy in
          LazyVStack {
            Textual content("Textual content 0")
              .id(0)
            

            // Simulating different views (these views will likely be added manually in the true app with out the ForEach)
            ForEach(0...50, id: .self) { index in
              Textual content("Textual content (index)")
            }
          }
          .navigationTitle("Title")
          .onChange(of: scrollToTop) {
            if scrollToTop {
              withAnimation { // works with out withAnimation provided that scroll isn't ongoing.
                proxy.scrollTo(0)
                // proxy.scrollTo(0, anchor: .backside) would not work with any anchor as properly
              }
              scrollToTop = false
            }
          }
        }
      }
    }
  }
}

tried setting anchor of scrollTo, not working
tried with out withAnimation. This works (though it is ugly) if scrolling isn’t ongoing. For those who faucet the tab whereas scroll continues to be taking place the behaviour is even stranger.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments