https://kotlinlang.org logo
#ios
Title
# ios
c

Christopher Mederos

11/22/2023, 11:45 PM
I'm having trouble maintaining scroll position when a View within a ScrollView changes size. I have a list of items, and each can be expanded to show some additional content. However, when expanding/collapsing the item, the scroll position sometimes jumps about. Is there a way to maintain scroll position when one item changes size? Alternatively, is this expanding style inappropriate on iOS? If so, is there a recommended best practice for showing more content (like seeing "more comments", expanding a quote, see a longer caption, etc.)
Copy code
struct MyList: View {
    var items: [String] = ["Item A", "Item B", "Item C", "Item D", "Item E", "Item F", "Item G", "Item H", "Item I", "Item J" ]
    
    var body: some View {
        ScrollView {
            LazyVStack(alignment: .center) {
                ForEach(items, id: \.self) { item in
                    ItemView(item: item)
                }
            }
            .background(.ultraThinMaterial)
        }
    }
}

struct ItemView: View {
    var item: String
    
    @State var expanded: Bool = false
    
    var body: some View {
        
        VStack {
            Text(item)
            Spacer(minLength: 50)
            Button("Expand/Collapse") {
                expanded.toggle()
            }
            if expanded {
                Text("Shown When Expanded")
                Text("\n -\n -\n -\n -\n -\n -\n -\n -\n -\n -\n -\n -")
            }
        }
        .frame(maxWidth: .infinity)
        .background()
        .padding(.bottom)
    }
}