Created
July 31, 2020 02:46
-
-
Save nataliapanferova/267e93b76c46184b37fd8bfc751ae98e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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