Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save nataliapanferova/267e93b76c46184b37fd8bfc751ae98e to your computer and use it in GitHub Desktop.

Select an option

Save nataliapanferova/267e93b76c46184b37fd8bfc751ae98e to your computer and use it in GitHub Desktop.
import SwiftUI
struct Item: Identifiable {
let id = UUID()
let name: String
}
struct ContentView: View {
@State private var items = [Item(name: "Item 1"), Item(name: "Item 2"), Item(name: "Item 2")]
@State private var itemToSetVisible: UUID? = nil
var body: some View {
HStack(spacing: 0) {
ScrollViewReader { scrollProxy in
ScrollView {
VStack(spacing: 0) {
ForEach(items) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.frame(height: 100)
.background(Color.gray)
.id(item.id)
.transition(.slide)
}
}
}
.onChange(of: self.itemToSetVisible) { item in
guard item != nil else { return }
withAnimation {
scrollProxy.scrollTo(item)
}
}
}
Divider()
Button("Add Item") {
let newItem = Item(name: "Item \(self.items.count + 1)")
withAnimation {
self.items.append(newItem)
}
self.itemToSetVisible = newItem.id
}
.padding()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment