0

I'm trying to preview my music player app (specifically, trying to view a "Now Playing" bar above a tab bar). I am getting the error "Static method 'buildExpression' requires that 'MyApp' conform to 'View'" in response to the last line of the code (i.e. the preview of "MyApp") -- any idea why?

import SwiftUI

class BottomPlayer: ObservableObject {
    @Published
    var show: Bool = false
}

@main
struct MyApp: App {
    var bottomPlayer: BottomPlayer = BottomPlayer()

       var body: some Scene {
           WindowGroup {
               ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
                   ContentView()
                   if bottomPlayer.show {
                       BottomPlayerView()
                           .offset(y: -40)
                   }
               }
               .environmentObject(bottomPlayer)
           }
       }
   }

struct MyApp_Previews: PreviewProvider {
        static var previews: some View {
            MyApp()

I tried swapping "MyApp()" in the preview section with "WindowGroup" or other sub-views, but that did not work either.

hmn70
  • 1

1 Answers1

1

You can only preview Views. MyApp is not a View, but an App, so you cannot preview it.

Create a View that contains the body of your App and preview that.

struct RootView: View {
  let bottomPlayer: BottomPlayer = BottomPlayer()

  var body: some View {
    ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
      ContentView()
      if bottomPlayer.show {
        BottomPlayerView()
          .offset(y: -40)
        }
      }
    }
    .environmentObject(bottomPlayer)
  }
}

struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      RootView()
    }
  }
}

struct RootView_Previews: PreviewProvider {
  static var previews: some View {
    RootView()
  }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116