aSwiftUI calling background causes infinite re-render crash

Viewed 41

Why does the following SwiftUI code produce a crash when calling background(Color.white)? (100% reproducible for me)

    struct ContentView: View {     
        var body: some View {         
            let _ = print("rendering")         
            background(Color.white)     
        } 
    }

I (now) understand this is not the way to set a background color, but the behavior still seems unexpected. The console prints "rendering" ~30 times, then crashes. Shouldn't SwiftUI produce a warning or an error here?

0x185a24fc8 <+8>: stp x28, x27, [sp, #0x90]

Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d037fd0)

1 Answers

You are calling self.background inside the body of your View.

The background view modifier modifies the view it is applied to, in this case, self, since it is called on self. This creates an infinite loop, since to apply background, the system tries to evaluate body, which then calls background again.

You either need to call background on another View, such as a

Color.clear // can replace this with any other View, such as Text("Hello world")
    .background(Color.white)

or you even better, you should simply return Color.white in your body if you want to return a white color.

struct ContentView: View {     
    var body: some View {         
        Color.white  
    } 
}

The Color.clear example is equivalent to simply returning Color.white, so don't use that in production code, I've just included it as an example.

Related