Post

Replies

Boosts

Views

Activity

Reply to Keep ScrollView position when adding items on the top
Repost of the Accepted Reply with a VStack added to the safeAreaInset and a background to the individual items within to make it readable and all the buttons clickable. @State var data: [String] = (0 ..< 25).map { String($0) } @State var dataID: String? var body: some View { ScrollView { VStack { Text("Header") //.background(.white) LazyVStack { ForEach(data, id: \.self) { item in Color.red .frame(width: 100, height: 100) .overlay { Text("\(item)") .padding() .background() } } } .scrollTargetLayout() } } .scrollPosition(id: $dataID) .safeAreaInset(edge: .bottom) { VStack { Text("\(Text("Scrolled").bold()) \(dataIDText)") .background(.white) Spacer() Button { dataID = data.first } label: { Label("Top", systemImage: "arrow.up") .background(.white) } Button { dataID = data.last } label: { Label("Bottom", systemImage: "arrow.down") .background(.white) } Menu { Button("Prepend") { let next = String(data.count) data.insert(next, at: 0) } Button("Append") { let next = String(data.count) data.append(next) } Button("Remove First") { data.removeFirst() } Button("Remove Last") { data.removeLast() } } label: { Label("More", systemImage: "ellipsis.circle") .background(.white) } } } } var dataIDText: String { dataID.map(String.init(describing:)) ?? "None" } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’23