You can use enumerated()
along with ForEach
to track an index of the array and use it to hide and show your button. Something like this.
struct ContentView: View {
let items = (1...50).map(String.init)
@State private var showScrollButton = false
var body: some View {
ScrollViewReader { reader in
ZStack(alignment: .bottomTrailing) {
List {
let enumerated = items.enumerated().map({ $0 })
ForEach(enumerated, id: \.element) { (index, item) in
Text(item)
.id(index)
.onAppear {
guard index == 0, showScrollButton else {
return
}
showScrollButton = false
}
.onDisappear {
guard index == 0, !showScrollButton else {
return
}
showScrollButton = true
}
}
}
if showScrollButton {
Button(action: {
withAnimation {
reader.scrollTo(0, anchor: .top)
}
}, label: {
Image(systemName: "chevron.up.circle")
.font(.largeTitle)
.foregroundColor(.black)
.padding()
.padding(.trailing)
})
}
}
}
}
}