ScrollView with .viewAligned and .scrollPosition() not updating on orientation (size) changes

The scroll position is not updated when orientation changes in a ScrollView with .scrollTargetBehavior(.viewAligned) and .scrollPosition().

import SwiftUI

struct ContentView: View {
    let colors: [Color] = [.red, .yellow, .cyan, .blue, .teal, .brown, .orange, .indigo]
    @State private var selected: Int? = 0
    
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 0) {
                ForEach(0..<colors.count, id: \.self) { index in
                    Rectangle()
                        .fill(colors[index])
                        .containerRelativeFrame(.horizontal)
                        .overlay {
                            Text(colors[index].description)
                        }
                }
            }
            .scrollTargetLayout()
        }
        .scrollPosition(id: $selected)
        .scrollTargetBehavior(.viewAligned)
    }
}

#Preview {
    ContentView()
}

@main
struct ViewAlignedScrollBugApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Tested on Xcode 15.3 (15E204a), iOS 17.3.1 iPhone, iOS 17.4 Simulator.

Bug report FB13685677 filed with Apple.

  • Another possible bug with this code: in landscape orientation the scrollable content is not clipped, although ScrollView should clip its content, by default. Adding a small horizontal padding to the container clips the content.

Add a Comment