Reputation: 645
I am working on miniplayer in swiftUI so a rectangle view will be universally top across the application. I have tried about ZStack
but currently its only achieving on single view. Can you please tell how can I create above all view ?
Upvotes: 4
Views: 2343
Reputation: 1256
You can do that with @EnvironmentObject
ContentView.swift
import SwiftUI
class ContentViewModel: ObservableObject {
@Published var isPresented: Bool = false
}
struct ContentView: View {
@EnvironmentObject private var miniPlayer: ContentViewModel
var body: some View {
ZStack {
VStack {
if miniPlayer.isPresented == true {
HStack {
Color.blue
// your miniPlayer View
}
.frame(width: 200, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
}
Spacer()
Button("Show/hide MiniPlayer") {
miniPlayer.isPresented.toggle()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(ContentViewModel())
}
}
YourApp.swift
import SwiftUI
@main
struct ReplyToStackoverflowApp: App {
var contentVM: ContentViewModel = ContentViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(contentVM)
}
}
}
Upvotes: 1
Reputation: 257493
You can put in in the App.body
over ContentView
and use some environment or environment object to control its visibility from any place in view hierarchy, like
@main
struct SwiftUIApp: App {
@State private var showView = false
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.showCoverView, $showView)
.overlay(Group {
if showView {
Text("Your top view here") // << here !!
}
})
}
}
}
struct ShowCoverViewKey: EnvironmentKey {
static var defaultValue: Binding<Bool> = .constant(false)
}
extension EnvironmentValues {
var showCoverView: Binding<Bool> {
get { self[ShowCoverViewKey.self] }
set { self[ShowCoverViewKey.self] = newValue }
}
}
Upvotes: 3