Reputation: 1587
I am new to SwiftUI. I am trying to add blur view with the app logo when the app enters into the background for hiding secure information. I tried the below code. It's showing blur as expected. But I want to display the view+app logo.
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
@State var blurRadius : CGFloat = 0
var body: some View {
VStack{
MainView()
}.blur(radius: blurRadius)
.onChange(of: scenePhase, perform: { value in
switch value {
case .active : withAnimation { blurRadius = 0 }
case .inactive: withAnimation { blurRadius = 15 }
case .background:
blurRadius = 20
@unknown default: print("Unknown")
}
})
}
}
Result:
Someone please suggests how to achieve that?
Upvotes: 2
Views: 1794
Reputation: 91
Honestly I suppose that previous answer is a bad solution. You should copy on every screen it. Try this:
static let appWindow = UIApplication.shared.connectedScenes.map({ $0 as? UIWindowScene }).compactMap({ $0 }).first?.windows.first
Then just add it on the tabBar, or on the main ContentView
:
@Environment(\.scenePhase) var scenePhase
@State private var coverImage: UIVisualEffectView?
private func addBluredView() {
coverImage = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterialDark))
if let coverImage {
coverImage.frame = AppInfo.appWindow!.screen.bounds
AppSettings.appWindow?.addSubview(coverImage)
}
}
and handle it:
.onChange(of: scenePhase) { newPhase in
switch newPhase {
case .inactive:
addBluredView()
case .active:
coverImage?.removeFromSuperview()
@unknown default:
break
}
}
Upvotes: -1
Reputation: 52387
You could use a ZStack
and place your logo image on top whenever there's a blur in place:
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
@State var blurRadius : CGFloat = 0
var body: some View {
ZStack {
VStack{
MainView()
}
.blur(radius: blurRadius)
.onChange(of: scenePhase, perform: { value in
switch value {
case .active : withAnimation { blurRadius = 0 }
case .inactive: withAnimation { blurRadius = 15 }
case .background:
blurRadius = 20
@unknown default: print("Unknown")
}
})
if blurRadius != 0 {
Image("logo")
}
}
}
}
This is assuming your app logo is added to the project's assets as "logo". Obviously, you may want to do some modifications like .resizable
or .frame
on the Image
Upvotes: 3