swiftuipaginationscrollview

ScrollView with pagination behavior makes app crash


I have a straightforward ScrollView that shows paging behavior like this:

import SwiftUI

struct ScrollTest: View {
   var body: some View {
     ScrollView {
        VStack{
            ForEach(0..<10, id: \.self) { index in
                Rectangle()
                    .ignoresSafeArea()
                    .frame(maxWidth:.infinity)
                    .containerRelativeFrame(.vertical, alignment:.center)
            }
        }
        .scrollTargetLayout()
     }
     .scrollTargetBehavior(.paging)
 }
}

The issue is that when launched on a simulator (or real device), the app crashes with a console error (it works just fine in the preview):

"Invalid frame dimension (negative or non-finite). *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer bounds contains NaN: [0 nan; 388 inf]. Layer: <CALayer:0x600000258fa0; position = CGPoint (194 inf); bounds = CGRect (0 0; 388 inf); delegate = <SwiftUI.HostingScrollView: 0x10282c200; baseClass = UIScrollView; frame = (0 nan; 388 inf); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x600000c8bdb0>; layer = <CALayer: 0x600000258fa0>; contentOffset: {0, 0}; contentSize: {388, 70.333333333333329}; adjustedContentInset: {nan, 0, 0, 0}>; sublayers = (<CALayer: 0x600000258280>, <CALayer: 0x6000002a1b40>); opaque = YES; masksToBounds = YES; allowsGroupOpacity = YES; >'"

The problem disappears when I remove the ".containerRelativeFrame(.vertical, alignment:.center)" modifier, but the scrolling behavior I desire (TikTok-style scrolling) is not achieved.

Has anyone encountered a similar problem? Thank you.


Solution

  • After going through a long process of trial and error, I discovered that the issue stemmed from having a ScrollView nested inside another ScrollView. Removing the parent ScrollView fixed the problem.