SwiftUI - Scrolling to correct position of the Image when it has .position(..)

42 Views Asked by At

If Image has a .position, then ScrollView is not scrolling correctly. In this example I have a blue baseball ball and a small star with .position. When I push a button I am excepting to get a star in the center of the screen but everything is scrolled to a position where a star would be WITHOUT .position(..). Why? How to scroll to correct position of the star?

struct ContentView: View {
    
    var body: some View {
        ScrollViewReader { proxy in
            Button("Scroll to small Image") {
                withAnimation {
                    proxy.scrollTo(111, anchor: .center)
                }
            }
            
            ScrollView([.horizontal, .vertical]) {
                ZStack {
                    Image(systemName: "baseball.circle")
                        .resizable()
                        .aspectRatio(1, contentMode: .fit)
                        .frame(width: 800, height: 1200)
                        .foregroundColor(.blue)
                    
                    Image(systemName: "star")
                        .resizable()
                        .aspectRatio(1, contentMode: .fit)
                        .frame(width: 80, height: 80)
                        .position(CGPoint(x: 180, y: 400)) // <----- not scrolling correctly to this position
                        .foregroundColor(.red)
                        .id(111)
                }
                .scrollTargetLayout()
            }
        }
    }
}
0

There are 0 best solutions below