How do you blur the background in a SwiftUI macOS application? - swift

I want to make the highlighted section transparent and blurred similar to other macOS applications. I found articles online on how to use an NSViewController to blur which I don't fully understand. I am new to swift and don't yet understand how to use Viewcontrollers. My code is below. Any help would be appreciated!
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
GeometryReader { geometry in
NavigationView{
HStack(spacing: 0) {
ZStack{
Text("BitMessenger")
.font(.title)
.fontWeight(.light)
.foregroundColor(Color.white)
}
.frame(width: geometry.size.width/2, height: geometry.size.height+20)
.background(Color(red: 0.07, green: 0.07, blue: 0.07, opacity: 1.0))
VStack{
HStack {
Text("Sign Up")
.font(.headline)
.padding(.top, 30.0)
Spacer()
}
HStack {
Text("Welcome to BitMessenger")
.font(.subheadline)
.foregroundColor(Color.gray)
.padding(.top, 10.0)
Spacer()
}
Form {
VStack{
HStack {
Text("Full Name")
.font(.caption)
.foregroundColor(Color.white)
.padding(.top, 10.0)
Spacer()
}
TextField("ex. John Doe", text: /*#START_MENU_TOKEN#*//*#PLACEHOLDER=Value#*/.constant("")/*#END_MENU_TOKEN#*/)
HStack {
Text("Email Address")
.font(.caption)
.foregroundColor(Color.white)
.padding(.top, 10.0)
Spacer()
}
TextField("doejohn#example.com", text: /*#START_MENU_TOKEN#*//*#PLACEHOLDER=Value#*/.constant("")/*#END_MENU_TOKEN#*/)
HStack {
Text("Password")
.font(.caption)
.foregroundColor(Color.white)
.padding(.top, 10.0)
Spacer()
}
TextField("AIOFHWaowhf", text: /*#START_MENU_TOKEN#*//*#PLACEHOLDER=Value#*/.constant("")/*#END_MENU_TOKEN#*/)
HStack {
Button(action: /*#START_MENU_TOKEN#*/{}/*#END_MENU_TOKEN#*/) {
Text("Register")
.padding(.horizontal, 10.0)
}
.padding(.all)
}
}
}
.padding(.top)
Spacer()
NavigationLink(destination: ContentView()) {
Text("Already have an Account? Login")
.font(.caption)
.foregroundColor(Color.gray)
.background(Color.clear)
}
.padding(.bottom)
.foregroundColor(Color.clear)
}
.padding(.horizontal, 30.0)
.frame(width: geometry.size.width / 2, height: geometry.size.height+20)
.background(Color.black.opacity(0.9))
}.edgesIgnoringSafeArea(.all)
}
}
.edgesIgnoringSafeArea(.all)
.frame(width: 750.0, height: 500.0)
}
}
}
class MyViewController: NSViewController {
var visualEffect: NSVisualEffectView!
override func loadView() {
super.loadView()
visualEffect = NSVisualEffectView()
visualEffect.translatesAutoresizingMaskIntoConstraints = false
visualEffect.material = .dark
visualEffect.state = .active
visualEffect.blendingMode = .behindWindow
view.addSubview(visualEffect)
visualEffect.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
visualEffect.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
visualEffect.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
visualEffect.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

You don't really need to subclass NSViewController. What you need is - NSVisualEffectView from AppKit,
A view that adds translucency and vibrancy effects to the views in your interface.
Since the NSVisualEffectView is not yet available in SwiftUI, you can wrap it using NSViewRepresentable pretty much like every AppKit control not available in SwiftUI.
You can do it like this -
import SwiftUI
struct VisualEffectView: NSViewRepresentable
{
let material: NSVisualEffectView.Material
let blendingMode: NSVisualEffectView.BlendingMode
func makeNSView(context: Context) -> NSVisualEffectView
{
let visualEffectView = NSVisualEffectView()
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.state = NSVisualEffectView.State.active
return visualEffectView
}
func updateNSView(_ visualEffectView: NSVisualEffectView, context: Context)
{
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
}
}
You can then use it as a standalone View-
VisualEffectView(material: NSVisualEffectView.Material.contentBackground, blendingMode: NSVisualEffectView.BlendingMode.withinWindow)
or use it as a background modifier to your highlighted VStack like this -
.background(VisualEffectView(material: NSVisualEffectView.Material.contentBackground, blendingMode: NSVisualEffectView.BlendingMode.withinWindow))
Go through the Apple Developer docs to learn more about the two blending modes. Also, play with the Material property to get the desired result.

This solution allows you to create a semiOpaqueWindow() type method that you can apply to a child of the View protocol, for example to a Rectangle shape here.
import SwiftUI
extension View {
public static func semiOpaqueWindow() -> some View {
VisualEffect().ignoresSafeArea()
}
}
struct VisualEffect : NSViewRepresentable {
func makeNSView(context: Context) -> NSView {
let view = NSVisualEffectView()
view.state = .active
return view
}
func updateNSView(_ view: NSView, context: Context) { }
}
struct ContentView : View {
var body: some View {
ZStack {
Rectangle.semiOpaqueWindow()
Text("Semi Transparent MacOS window")
}
}
}

Related

Increase tappable area Datepicker SwiftUI

I'm trying to build a custom datepicker which is working perfectly so far. The last thing I try to increase is the tappable area, which I prefer to be the entire shape. Currently, a user has to tap the Calendar picture for date selection.
I've experimented with Contentshape, increasing the frame and adding padding, but nothing works as expected. How can I increase the tappable area while keeping it looking like this? Ideally, a user could tap the area within the border and the picker pops up.
My code:
struct DatePickerView: View {
#State private var selectedDate = Date()
var body: some View {
VStack(alignment: .leading) {
Text("Datum")
.foregroundColor(.black)
HStack {
Text("\(selectedDate.formatted())")
Spacer()
ZStack {
DatePicker("", selection: $selectedDate, in: ...Date(), displayedComponents: .date)
.datePickerStyle(.compact)
.labelsHidden()
.accentColor(.black)
SwiftUIWrapper {
Image(systemName: "calendar")
.resizable()
.frame(width: 18, height: 20)
}
.allowsHitTesting(false)
}
.frame(width: 18, height: 20)
}
.padding(16)
.overlay {
RoundedRectangle(cornerRadius: 8)
.strokeBorder(
style: StrokeStyle(
lineWidth: 0.5
)
)
.foregroundColor(.black)
}
}
}
}
struct DatePicker_Previews: PreviewProvider {
static var previews: some View {
DatePickerView()
}
}
struct SwiftUIWrapper<T: View>: UIViewControllerRepresentable {
let content: () -> T
func makeUIViewController(context: Context) -> UIHostingController<T> {
UIHostingController(rootView: content())
}
func updateUIViewController(_ uiViewController: UIHostingController<T>, context: Context) {}
}
Managed to make it work with some minor tweaks. Especially scaleEffect!
.compositingGroup()
.scaleEffect(x: 10, y: 1.5)
.clipped()
Endresult:
struct DatePickerView: View {
#State private var selectedDate = Date()
var body: some View {
VStack(alignment: .leading) {
Text("Datum")
.foregroundColor(.gray)
ZStack {
DatePicker("", selection: $selectedDate, in: ...Date(), displayedComponents: .date)
.datePickerStyle(.compact)
.labelsHidden()
.accentColor(.black)
.compositingGroup()
.scaleEffect(x: 10, y: 1.5)
.clipped()
SwiftUIWrapper {
HStack {
Text(selectedDate.formatted())
Spacer()
Image(systemName: "calendar")
.resizable()
.frame(width: 18, height: 20)
}
.padding(16)
.background(Color.white)
}
.padding(.vertical, 32)
.fixedSize(horizontal: false, vertical: true)
.allowsHitTesting(false)
}
.overlay (
RoundedRectangle(cornerRadius: 8)
.strokeBorder(
style: StrokeStyle(lineWidth: 0.5)
)
.foregroundColor(.black)
)
}
}
}
struct SwiftUIWrapper<T: View>: UIViewControllerRepresentable {
let content: () -> T
func makeUIViewController(context: Context) -> UIHostingController<T> {
UIHostingController(rootView: content())
}
func updateUIViewController(_ uiViewController: UIHostingController<T>, context: Context) {}
}
struct DatePicker_Previews: PreviewProvider {
static var previews: some View {
DatePickerView()
}
}

How to expand Detail View to full screen with SwiftUI?

I have a list view embedded in a Navigation View, however, this Navigation View is only about the screen height. This list links to a detailed view, and when a row is tapped, the Detail View only takes up half of the screen. I would like it to open a completely new window.
Screenshots:
The code is used is the following:
import SwiftUI
import CoreData
extension UIScreen{
static let screenWidth = UIScreen.main.bounds.size.width
static let screenHeight = UIScreen.main.bounds.size.height
static let screenSize = UIScreen.main.bounds.size
}
let topCardHeight: CGFloat = 350
struct HomeView: View {
#Environment(\.managedObjectContext) var moc
#FetchRequest(entity: SavedPoem.entity(), sortDescriptors: []) var savedpoems : FetchedResults<SavedPoem>
var body: some View {
VStack {
VStack (alignment: .center){
Text("Today's Poem, November 18th...")
.font(.subheadline)
.foregroundColor(.white)
.padding(.bottom)
.padding(.top, 75)
Text("No Man Is An Island")
.font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.bottom,1)
Text("by John Donne")
.font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.bottom, 35)
Button(action: {}) {
Text("Read Now")
.fontWeight(/*#START_MENU_TOKEN#*/.bold/*#END_MENU_TOKEN#*/)
.font(.subheadline)
.foregroundColor(.white)
.padding(15)
.border(Color.white, width: 3)
}
}
.frame(width: UIScreen.screenWidth, height: topCardHeight, alignment: .top)
.background(Color.black)
.edgesIgnoringSafeArea(.top)
.edgesIgnoringSafeArea(.bottom)
.padding(.bottom, 0)
NavigationView{
List{
ForEach(savedpoems, id:\.title) {SavedPoem in
NavigationLink (destination: ContentView()){
ZStack {
Rectangle().fill(Color.white)
.frame(width: UIScreen.main.bounds.width - 32, height: 70)
.cornerRadius(10).shadow(color: .gray, radius: 4)
HStack {
VStack (alignment: .leading){
Text("\(SavedPoem.title ?? "")").font(.headline)
.lineLimit(1)
Text("\(SavedPoem.author ?? "")").font(.subheadline)
.foregroundColor(.secondary)
}
Spacer()
}.padding()
}
// }.onDelete(perform: remove)
}
}
}
.navigationTitle("My Saved Poems")
.navigationBarHidden(true)
.edgesIgnoringSafeArea(.top)
.padding(.top, 0)
}
}
// func remove(at offsets : IndexSet) {
// for index in offsets {
// let delete = SavedPoem[index]
// self.moc.delete(delete)
// }
// try? self.moc.save()
// }
}
Any ideas? Thanks in advance.
If you need the same UI:
(The navigation view at the bottom of your top view) , here is a solution for it .
var body: some View {
#EnvironmentObject var sharedViewModel : SharedViewModel
VStack {
VStack (alignment: .center){
if sharedViewModel.currentPageIsHome {
// your top view body here ..
}
}
NavigationView{\*....*\}
}
}.onAppear {
sharedViewModel.currentPageIsHome = true
}.onDisappear {
sharedViewModel.currentPageIsHome = false
}
And you need to create an Observable object
class SharedViewModel: ObservableObject {
#Published var currentPageIsHome = false
}
And don't forget to initialize it in your SceneDelegate
ContentView().environmentObject(SharedViewModel())
Or
Clear version :
change your view hierarchy to :
NavigationView {
List{
Section(header: YourTopView()) {
// ... your list content
}
}
}

View don't disappear with the way it should

I am trying to make the yellow views disappear from bottom and top with a nice and smooth animation. (slide/move to top/bottom + fadding and keep the middle view taking the whole space)
This is my current state, and it is everything but smooth and nice haha. but it works.
import SwiftUI
struct ContentView: View {
#State var isInterfaceHidden: Bool = false
var body: some View {
VStack(spacing: 0, content: {
if !isInterfaceHidden {
Rectangle()
.id("animation")
.foregroundColor(Color.yellow)
.frame(height: 40)
.transition(AnyTransition.move(edge: .top).combined(with: .opacity).animation(.linear))
}
Rectangle()
.id("animation2")
.foregroundColor(Color.red)
.transition(AnyTransition.opacity.animation(Animation.linear))
/// We make sure it won't cover the top and bottom view.
.zIndex(-1)
.background(Color.red)
.onTapGesture(perform: {
DispatchQueue.main.async {
self.isInterfaceHidden.toggle()
}
})
if !isInterfaceHidden {
Rectangle()
.id("animation3")
.foregroundColor(Color.yellow)
.frame(height: 80)
.transition(AnyTransition.move(edge: .bottom).combined(with: .opacity).animation(.linear))
}
})
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
Current animation:
Edit3: Thanks to #Andrew I was able to progress in a better state.
But now I have a sort of jerky animation.
Any thoughts?
I may have found a solution for you:
import SwiftUI
struct ContentView: View {
#State var isInterfaceHidden: Bool = false
var body: some View {
VStack(spacing: 0, content: {
if !isInterfaceHidden {
Rectangle()
.id("animation")
.foregroundColor(Color.yellow)
.frame(height: 40)
.transition(.topViewTransition)
}
Rectangle()
.id("animation2")
.foregroundColor(Color.red)
/// We make sure it won't cover the top and bottom view.
.zIndex(-1)
.background(Color.red)
.onTapGesture(perform: {
DispatchQueue.main.async {
self.isInterfaceHidden.toggle()
}
})
if !isInterfaceHidden {
Rectangle()
.id("animation3")
.foregroundColor(Color.yellow)
.frame(height: 80)
.transition(.bottomViewTransition)
}
})
.navigationBarTitle("")
.navigationBarHidden(true)
.animation(.easeInOut)
}
}
extension AnyTransition {
static var topViewTransition: AnyTransition {
let transition = AnyTransition.move(edge: .top)
.combined(with: .opacity)
return transition
}
static var bottomViewTransition: AnyTransition {
let transition = AnyTransition.move(edge: .bottom)
.combined(with: .opacity)
return transition
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Simply set Z index for the both of your yellow views anything higher than the default value of 1.0. This way SwiftUI will make sure they won't be covered by the red view.
The modifier to do that is .zIndex()
A simpler solution
struct Test: View {
#State private var isHiding = false
var body: some View {
ZStack {
Rectangle()
.foregroundColor(.yellow)
.frame(width: 200, height: 100)
Rectangle()
.foregroundColor(.red)
.frame(width: 200, height: isHiding ? 100 : 80)
.onTapGesture {
withAnimation {
self.isHiding.toggle()
}
}
}
}
}

SwiftUI - in sheet have a fixed continue button that is not scrollable

As you can see even though I am trying to pull the sheet down, the continue button does not move down. How can I make my sheet to behave like that? In my app the continue button moves offscreen. This is how my app looks when the sheet is pulled down slightly:
I have also attached my code below, it looks aesthetic on both landscape and portrait orientation. Is there a way to pull this off without ruining how it looks on landscape on smaller devices such as the iPhone 7?
import SwiftUI
struct IntroView: View {
#State private var animationAmount: CGFloat = 1
#Environment(\.presentationMode) var presentationMode
#Environment(\.verticalSizeClass) var sizeClass
var body: some View {
VStack {
VStack {
Spacer()
if sizeClass == .compact {
HStack {
Text("Welcome to Demo").fontWeight(.heavy)
Text("App").foregroundColor(.orange).fontWeight(.heavy)
}
.padding(.bottom, 10)
}
else {
Text("Welcome to").fontWeight(.heavy)
HStack {
Text("Demo").fontWeight(.heavy)
Text("App").foregroundColor(.orange).fontWeight(.heavy)
}
.padding(.bottom, 30)
}
}//Intro VStack close
.font(.largeTitle)
.frame(maxWidth: .infinity, maxHeight: 180)
VStack (spacing: 30) {
HStack (spacing: 20) {
Image(systemName: "sparkle")
.foregroundColor(.yellow)
.font(.title2)
.scaleEffect(animationAmount)
.onAppear {
let baseAnimation = Animation.easeInOut(duration: 1)
let repeated = baseAnimation.repeatForever(autoreverses: true)
return withAnimation(repeated) {
self.animationAmount = 1.5
}
}
VStack (alignment: .leading) {
Text("All new design").fontWeight(.semibold)
Text("Easily view all your essentials here.")
.foregroundColor(.gray)
}
Spacer()
}//HStack 1
.padding([.leading, .trailing], 10)
HStack (spacing: 20) {
Image(systemName: "pin")
.foregroundColor(.red)
.font(.title2)
.padding(.trailing, 5)
.scaleEffect(animationAmount)
.onAppear {
let baseAnimation = Animation.easeInOut(duration: 1)
let repeated = baseAnimation.repeatForever(autoreverses: true)
return withAnimation(repeated) {
self.animationAmount = 1.5
}
}
VStack (alignment: .leading) {
Text("Pin favourites").fontWeight(.semibold)
Text("You can pin your favourite content on all devices")
.foregroundColor(.gray)
}
Spacer()
}//HStack 2
.padding([.leading, .trailing], 10)
.frame(maxWidth: .infinity, maxHeight: 100)
HStack (spacing: 20) {
Image(systemName: "moon.stars.fill")
.foregroundColor(.blue)
.font(.title2)
.scaleEffect(animationAmount)
.onAppear {
let baseAnimation = Animation.easeInOut(duration: 1)
let repeated = baseAnimation.repeatForever(autoreverses: true)
return withAnimation(repeated) {
self.animationAmount = 1.5
}
}
VStack (alignment: .leading) {
Text("Flexible").fontWeight(.semibold)
Text("Supports dark mode")
.foregroundColor(.gray)
}
Spacer()
}//HStack 3
.padding([.leading, .trailing], 10)
}//VStack for 3 criterias
.padding([.leading, .trailing], 20)
Spacer()
Button {
presentationMode.wrappedValue.dismiss()
UserDefaults.standard.set(true, forKey: "LaunchedBefore")
} label: {
Text("Continue")
.fontWeight(.medium)
.padding([.top, .bottom], 15)
.padding([.leading, .trailing], 90)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(15)
}
.frame(maxWidth: .infinity, maxHeight: 100)
}//Main VStack
}
}
struct IntroView_Previews: PreviewProvider {
static var previews: some View {
IntroView()
}
}
Here is a demo of possible approach (tuning & effects are out of scope - try to make demo code short). The idea is to inject UIView holder with button above sheet so it persist during sheet drag down (because as findings shown any dynamic offsets gives some ugly undesired shaking effects).
Tested with Xcode 12 / iOS 14
// ... your above code here
}//VStack for 3 criterias
.padding([.leading, .trailing], 20)
Spacer()
// button moved from here into below background view !!
}.background(BottomView(presentation: presentationMode) {
Button {
presentationMode.wrappedValue.dismiss()
UserDefaults.standard.set(true, forKey: "LaunchedBefore")
} label: {
Text("Continue")
.fontWeight(.medium)
.padding([.top, .bottom], 15)
.padding([.leading, .trailing], 90)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(15)
}
})
//Main VStack
}
}
struct BottomView<Content: View>: UIViewRepresentable {
#Binding var presentationMode: PresentationMode
private var content: () -> Content
init(presentation: Binding<PresentationMode>, #ViewBuilder _ content: #escaping () -> Content) {
_presentationMode = presentation
self.content = content
}
func makeUIView(context: Context) -> UIView {
let view = UIView()
DispatchQueue.main.async {
if let window = view.window {
let holder = UIView()
context.coordinator.holder = holder
// simple demo background to make it visible
holder.layer.backgroundColor = UIColor.gray.withAlphaComponent(0.5).cgColor
holder.translatesAutoresizingMaskIntoConstraints = false
window.addSubview(holder)
holder.heightAnchor.constraint(equalToConstant: 140).isActive = true
holder.bottomAnchor.constraint(equalTo: window.bottomAnchor, constant: 0).isActive = true
holder.leadingAnchor.constraint(equalTo: window.leadingAnchor, constant: 0).isActive = true
holder.trailingAnchor.constraint(equalTo: window.trailingAnchor, constant: 0).isActive = true
if let contentView = UIHostingController(rootView: content()).view {
contentView.backgroundColor = UIColor.clear
contentView.translatesAutoresizingMaskIntoConstraints = false
holder.addSubview(contentView)
contentView.topAnchor.constraint(equalTo: holder.topAnchor, constant: 0).isActive = true
contentView.bottomAnchor.constraint(equalTo: holder.bottomAnchor, constant: 0).isActive = true
contentView.leadingAnchor.constraint(equalTo: holder.leadingAnchor, constant: 0).isActive = true
contentView.trailingAnchor.constraint(equalTo: holder.trailingAnchor, constant: 0).isActive = true
}
}
}
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
if !presentationMode.isPresented {
context.coordinator.holder.removeFromSuperview()
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator {
var holder: UIView!
deinit {
holder.removeFromSuperview()
}
}
}
Simply add that :
.sheet(isPresented: self.$visibleSheet) {
IntroView(visibleSheet: self.$visibleSheet)
.presentation(shouldDismissOnDrag: false)
}
https://stackoverflow.com/a/61239704/7974174 :
extension View {
func presentation(shouldDismissOnDrag: Bool, onDismissalAttempt: (()->())? = nil) -> some View {
ModalView(view: self, shouldDismiss: shouldDismissOnDrag, onDismissalAttempt: onDismissalAttempt)
}
}
struct ModalView<T: View>: UIViewControllerRepresentable {
let view: T
let shouldDismiss: Bool
let onDismissalAttempt: (()->())?
func makeUIViewController(context: Context) -> UIHostingController<T> {
UIHostingController(rootView: view)
}
func updateUIViewController(_ uiViewController: UIHostingController<T>, context: Context) {
uiViewController.parent?.presentationController?.delegate = context.coordinator
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIAdaptivePresentationControllerDelegate {
let modalView: ModalView
init(_ modalView: ModalView) {
self.modalView = modalView
}
func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
modalView.shouldDismiss
}
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
modalView.onDismissalAttempt?()
}
}
}
It disables the sheet closing by dragging the sheet down. If you want to close the sheet with the button do not use presentationMode anymore. Pass a binding of self.$visibleSheet then modify to false from inside...

What might be causing this animation bug with SwiftUI and NavigationView?

I've been experimenting with some SwiftUI layouts and one of the things that I wanted to try out was creating a simple circular progress ring. After playing around with the code for a while I managed to get everything working the way I was hoping for it to, at least for a prototype. The issue arrises when I embed this view inside a SwiftUI NavigationView. Now, every time I run the app in the canvas, simulator, or on a device, the initial loading of the progress ring has the entire view slowly sliding up into position.
This is a simple prototype, just messing around with the new SwiftUI tools. After some experimentation, I've found that if I remove the NavigationView the ring acts like it's meant to from the beginning. I'm not seeing an obvious reason for why this issue is occurring though.
import SwiftUI
struct ProgressRing_ContentView: View {
#State var progressToggle = false
#State var progressRingEndingValue: CGFloat = 0.75
var ringColor: Color = Color.green
var ringWidth: CGFloat = 20
var ringSize: CGFloat = 200
var body: some View {
TabView{
NavigationView{
VStack{
Spacer()
ZStack{
Circle()
.trim(from: 0, to: progressToggle ? progressRingEndingValue : 0)
.stroke(ringColor, style: StrokeStyle(lineWidth: ringWidth, lineCap: .round, lineJoin: .round))
.background(Circle().stroke(ringColor, lineWidth: ringWidth).opacity(0.2))
.frame(width: ringSize, height: ringSize)
.rotationEffect(.degrees(-90.0))
.animation(.easeInOut(duration: 1))
.onAppear() {
self.progressToggle.toggle()
}
Text("\(Int(progressRingEndingValue * 100)) %")
.font(.largeTitle)
.fontWeight(.bold)
}
Spacer()
Button(action: {
self.progressRingEndingValue = CGFloat.random(in: 0...1)
}) { Text("Randomize")
.font(.largeTitle)
.foregroundColor(ringColor)
}
Spacer()
}
.navigationBarTitle("ProgressRing", displayMode: .inline)
.navigationBarItems(leading:
Button(action: {
print("Refresh Button Tapped")
}) {
Image(systemName: "arrow.clockwise")
.foregroundColor(Color.green)
}, trailing:
Button(action: {
print("Share Button Tapped")
}) {
Image(systemName: "square.and.arrow.up")
.foregroundColor(Color.green)
}
)
}
}
}
}
#if DEBUG
struct ProgressRing_ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ProgressRing_ContentView()
.environment(\.colorScheme, .light)
.previewDisplayName("Light Mode")
}
}
#endif
Above is the exact code that I'm currently working with. The actual animation of the ring sliding seems to be working how I expected it to, I'm just not sure why the entire ring itself is moving when embedded in a NavigationView.
You need to use explicit animations, instead of implicit. With implicit animations, any animatable parameter that changes, the framework will animate. Whenever possible, you should use explicit animations. Below is the updated code. Notice I remove the .animation() call and added two withAnimation() closures.
If you would like to expand your knowledge on implicit vs. explicit animations, check this link: https://swiftui-lab.com/swiftui-animations-part1/
struct ContentView: View {
#State var progressToggle = false
#State var progressRingEndingValue: CGFloat = 0.75
var ringColor: Color = Color.green
var ringWidth: CGFloat = 20
var ringSize: CGFloat = 200
var body: some View {
TabView{
NavigationView{
VStack{
Spacer()
ZStack{
Circle()
.trim(from: 0, to: progressToggle ? progressRingEndingValue : 0)
.stroke(ringColor, style: StrokeStyle(lineWidth: ringWidth, lineCap: .round, lineJoin: .round))
.background(Circle().stroke(ringColor, lineWidth: ringWidth).opacity(0.2))
.frame(width: ringSize, height: ringSize)
.rotationEffect(.degrees(-90.0))
.onAppear() {
withAnimation(.easeInOut(duration: 1)) {
self.progressToggle.toggle()
}
}
Text("\(Int(progressRingEndingValue * 100)) %")
.font(.largeTitle)
.fontWeight(.bold)
}
Spacer()
Button(action: {
withAnimation(.easeInOut(duration: 1)) {
self.progressRingEndingValue = CGFloat.random(in: 0...1)
}
}) { Text("Randomize")
.font(.largeTitle)
.foregroundColor(ringColor)
}
Spacer()
}
.navigationBarTitle("ProgressRing", displayMode: .inline)
.navigationBarItems(leading:
Button(action: {
print("Refresh Button Tapped")
}) {
Image(systemName: "arrow.clockwise")
.foregroundColor(Color.green)
}, trailing:
Button(action: {
print("Share Button Tapped")
}) {
Image(systemName: "square.and.arrow.up")
.foregroundColor(Color.green)
}
)
}
}
}
}