SwiftUI: How to delete a view after a certain time - ios

I have this animation code:
struct CheckmarkAnimation: View {
#State private var isAnimating = false
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(.green, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(.green)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.onAppear {
isAnimating.toggle()
}
}
}
I would like this view to disappear after the scaling effect on the checkmark ends. How do I do this?

Here are 2 ways to do it:
Change drawing color to .clear after 2 seconds
Here’s a way to have it disappear (turn invisible but still take up space). Change the drawing color to .clear after 2 seconds:
struct CheckmarkAnimation: View {
#State private var isAnimating = false
#State private var color = Color.green
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(color, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(color)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0.001)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.onAppear {
isAnimating.toggle()
withAnimation(.linear(duration: 0.01).delay(2)) {
color = .clear
}
}
}
}
Use .scaleEffect() on ZStack
Insert this scale animation before the .onAppear:
.scaleEffect(isAnimating ? 0.001 : 1)
.animation(.linear(duration: 0.01).delay(2), value: isAnimating)
.onAppear {
isAnimating.toggle()
}
Note: Use 0.001 instead of 0 in scaleEffect to avoid
ignoring singular matrix: ProjectionTransform
messages in the console.

.scaleEffect() on ZStack is an elegant solution.
struct CheckmarkAnimation: View {
#State private var isAnimating = false
#State private var color = Color.green
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(color, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(color)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.scaleEffect(isAnimating ? 0 : 1)
.animation(.linear(duration: 0.01).delay(2), value: isAnimating)
.onAppear {
isAnimating.toggle()
}
}
}
This code works and makes the view disappear^^

Related

Expandable Custom Segmented Picker in SwiftUI

I'm trying to create an expandable segmented picker in SwiftUI, I've done this so far :
struct CustomSegmentedPicker: View {
#Binding var preselectedIndex: Int
#State var isExpanded = false
var options: [String]
let color = Color.orange
var body: some View {
HStack {
ScrollView(.horizontal) {
HStack(spacing: 4) {
ForEach(options.indices, id:\.self) { index in
let isSelected = preselectedIndex == index
ZStack {
Rectangle()
.fill(isSelected ? color : .white)
.cornerRadius(30)
.padding(5)
.onTapGesture {
preselectedIndex = index
withAnimation(.easeInOut(duration: 0.5)) {
isExpanded.toggle()
}
}
}
.shadow(color: Color(UIColor.lightGray), radius: 2)
.overlay(
Text(options[index])
.fontWeight(isSelected ? .bold : .regular)
.foregroundColor(isSelected ? .white : .black)
)
.frame(width: 80)
}
}
}
.transition(.move(edge: .trailing))
.frame(width: isExpanded ? 80 : CGFloat(options.count) * 80 + 10, height: 50)
.background(Color(UIColor.cyan))
.cornerRadius(30)
.clipped()
Spacer()
}
}
}
Which gives this result :
Now, when it contracts, how can I keep showing the item selected and hide the others ? (for the moment, the item on the left is always shown when not expanded)
Nice job. You can add an .offset() to the contents of the ScollView, which shifts it left depending on the selection:
HStack {
ScrollView(.horizontal) {
HStack(spacing: 4) {
ForEach(options.indices, id:\.self) { index in
let isSelected = preselectedIndex == index
ZStack {
Rectangle()
.fill(isSelected ? color : .white)
.cornerRadius(30)
.padding(5)
.onTapGesture {
preselectedIndex = index
withAnimation(.easeInOut(duration: 0.5)) {
isExpanded.toggle()
}
}
}
.shadow(color: Color(UIColor.lightGray), radius: 2)
.overlay(
Text(options[index])
.fontWeight(isSelected ? .bold : .regular)
.foregroundColor(isSelected ? .white : .black)
)
.frame(width: 80)
}
}
.offset(x: isExpanded ? CGFloat(-84 * preselectedIndex) : 0) // <<< here
}
.transition(.move(edge: .trailing))
.frame(width: isExpanded ? 80 : CGFloat(options.count) * 80 + 10, height: 50)
.background(Color(UIColor.cyan))
.cornerRadius(30)
.clipped()
Spacer()
}
Here is another approach using .matchedGeometryEffect, which can handle different label widths without falling back to GeometryReader.
Based on expansionState it either draws only the selected item or all of them and .matchedGeometryEffect makes sure the animation goes smooth.
struct CustomSegmentedPicker: View {
#Binding var preselectedIndex: Int
#State var isExpanded = false
var options: [String]
let color = Color.orange
#Namespace var nspace
var body: some View {
HStack {
HStack(spacing: 8) {
if isExpanded == false { // show only selected option
optionLabel(index: preselectedIndex)
.id(preselectedIndex)
.matchedGeometryEffect(id: preselectedIndex, in: nspace, isSource: true)
} else { // show all options
ForEach(options.indices, id:\.self) { index in
optionLabel(index: index)
.id(index)
.matchedGeometryEffect(id: index, in: nspace, isSource: true)
}
}
}
.padding(5)
.background(Color(UIColor.cyan))
.cornerRadius(30)
Spacer()
}
}
func optionLabel(index: Int) -> some View {
let isSelected = preselectedIndex == index
return Text(options[index])
.fontWeight(isSelected ? .bold : .regular)
.foregroundColor(isSelected ? .white : .black)
.padding(8)
.background {
Rectangle()
.fill(isSelected ? color : .white)
.cornerRadius(30)
}
.onTapGesture {
preselectedIndex = index
withAnimation(.easeInOut(duration: 0.5)) {
isExpanded.toggle()
}
}
}
}

Swift UI loading indicator is not animating

I am trying to implement a button in swift UI that will show a loading indicator on click. but after the button click, the loading indicator is not animating.
{
Button(action: {
self.isLoading = true
}) {
HStack {
if isLoading {
Circle()
.trim(from: 0, to: 0.7)
.stroke(Color.green, lineWidth: 5)
.frame(width: 50, height: 50)
.rotationEffect(Angle(degrees: isLoading ? 360 : 0))
.animation(.default
.repeatForever(autoreverses: false), value: isLoading)
}
Text( isLoading ? "Processing" : "Submit")
.fontWeight(.semibold)
.font(.title)
}
}
.frame(width: 250, height: 50)
.background(.white)
}
It should be different states: one for transition, one for progress. So it is better to separate progress into different view
Tested with Xcode 13.4 / iOS 15.5
Note: it's better to use linear animation in this case
HStack {
if isLoading {
MyProgress() // << here !!
}
Text( isLoading ? "Processing" : "Submit")
.fontWeight(.semibold)
.font(.title)
}
and
struct MyProgress: View {
#State var isLoading = false
var body: some View {
Circle()
.trim(from: 0, to: 0.7)
.stroke(Color.green, lineWidth: 5)
.frame(width: 50, height: 50)
.rotationEffect(Angle(degrees: isLoading ? 360 : 0))
.animation(.linear
.repeatForever(autoreverses: false), value: isLoading)
.onAppear {
isLoading = true
}
}
}
Test module on GitHub

Swiftui animation calendar dates

In my app I want to show the passage of time by having a "calendar" transition from one date to the next, to the next, to the next, etc. So, for example, if I want to show the date transitioning from the 18th, to the 19th, to the 20th, I will show 18 for 1 second, then fade that out, fade in 19, fade that out, then fade in 20.
I have the following to show one date animating to the next (e.g. 18 > 19th):
struct Calendar: View {
#State var date: String
var body: some View {
VStack {
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black, lineWidth: 2)
.frame(width: 200, height: 200)
RoundedRectangle(cornerRadius: 20)
.fill(Color.red)
.frame(width: 200, height: 200)
.offset(y: 160)
.clipped()
.offset(y: -160)
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black, lineWidth: 2)
.frame(width: 200, height: 200)
.offset(y: 160)
.clipped()
.offset(y: -160)
Text(date).font(.system(size: 70.0))
.offset(y: 20)
}
Spacer()
Spacer()
}.padding()
}
}
and I call this in my code using:
ScrollView(showsIndicators: false) {
VStack {
Spacer()
ZStack {
if showseconddate == false {
Calendar(date: "18").animation(.easeInOut(duration: 1.0))
.transition(.opacity)
}
if showseconddate == true {
Calendar(date: "19").animation(.easeInOut(duration: 1.0))
.transition(.opacity)
}
Spacer()
}
}.onAppear {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
withAnimation(Animation.linear(duration: 0.5)) {
self.showseconddate.toggle()
self.showfirstdate.toggle() }
timer.invalidate()
}
}
}
This all works as intended, but I'm struggling to then expand this to a case where I want to show it transitioning through multiple dates, such as 18 > 19 >20 >21 etc. Does anyone know how to expand this, or to use an alternative solution? Any solution must fade out the old date, then fade in the new date. Many thanks!
Here's a relatively compact solution. Instead of relying on Bool values, it cycles through an array:
struct ContentView: View {
private var dates = ["18","19","20","21","22"]
#State private var dateIndex = 0
private let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
var body: some View{
ScrollView(showsIndicators: false) {
VStack {
Spacer()
ZStack {
Calendar(date: dates[dateIndex])
.transition(.opacity)
.id("date-\(dateIndex)")
Spacer()
}
}.onReceive(timer) { _ in
var newIndex = dateIndex + 1
if newIndex == dates.count { newIndex = 0 }
withAnimation(.easeInOut(duration: 0.5)) {
dateIndex = newIndex
}
}
}
}
}
I had reworked your code to get the animations running, I felt it was a bit annoying to watch the entire calendar flash, so I reworked it into a CalendarPage (I renamed Calendar to CalendarPage because Calendar is a Type in Swift) and CalendarView that takes the date and overlays it on the page.
CalendarPage is your Calendar with the date var and Text() removed:
struct CalendarPage: View {
var body: some View {
VStack {
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black, lineWidth: 2)
.frame(width: 200, height: 200)
RoundedRectangle(cornerRadius: 20)
.fill(Color.red)
.frame(width: 200, height: 200)
.offset(y: 160)
.clipped()
.offset(y: -160)
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black, lineWidth: 2)
.frame(width: 200, height: 200)
.offset(y: 160)
.clipped()
.offset(y: -160)
}
Spacer()
Spacer()
}.padding()
}
}
CalendarView uses the timer to increment your dates until you reach the endDate, and it only effects the opacity of the date itself, not the whole calendar:
struct CalendarView: View {
#State var date: Int = 0
#State var animate = false
#State var calendarSize: CGFloat = 20
let endDate = 31
// This keeps the font size consistent regardless of the size of the calendar
var fontSize: CGFloat {
calendarSize * 0.45
}
private let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
var body: some View {
CalendarPage(date: date.description)
.overlay(alignment: .bottom) {
VStack {
Text(date.description)
.font(.system(size: fontSize))
.opacity(animate ? 1 : 0)
}
.frame(height: calendarSize * 0.8)
}
.frame(width: 200, height: 200)
.readSize(onChange: { size in
calendarSize = min(size.width, size.height)
})
.onReceive(timer) { _ in
date += 1
withAnimation(.linear(duration: 0.3)) {
animate = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
if date != endDate {
withAnimation(.linear(duration: 0.2)) {
animate = false
}
} else {
timer.upstream.connect().cancel()
}
}
}
}
}
I also used a preference key to compute the height of the CalendarPage (though I could have hard coded it) using this View extension from FiveStars blog
extension View {
func readSize(onChange: #escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}
fileprivate struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

SwiftUI offset animation problem while in preparing bottomsheet

I wanted to make a bottomsheet in SwiftUI with my own efforts, I open it using animation, but my animation doesn't work when closing, what is the reason?
I wonder if the offset value is increasing with animation, is there a problem while it is decreasing I am not very good at SwiftUI so I could not fully understand the problem.
struct ContentView: View {
#State var isOpen = false
#State var offset = UIScreen.main.bounds.height / 3
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
Button(action: {
self.isOpen.toggle()
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 25.0)
.foregroundColor(.black)
Text("Open")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.white)
}
})
.buttonStyle(DefaultButtonStyle())
.frame(width: 300, height: 50, alignment: .center)
if isOpen {
GeometryReader { geometry in
VStack {
Spacer()
BottomSheet()
.frame(width: geometry.size.width,
height: geometry.size.height / 3,
alignment: .center)
.background(
Color.white
)
.offset(y: offset)
.onAppear(perform: {
withAnimation {
self.offset = 0
}
})
.onDisappear(perform: {
withAnimation {
self.offset = UIScreen.main.bounds.height / 3
}
})
}.ignoresSafeArea()
}
}
}
}
}
BottomSheet
struct BottomSheet: View {
var body: some View {
Text("Hello, World!")
}
}
onDisappear gets called when the view was removed, that's the reason custom animation not working :
struct ContentView: View {
#State var isOpen = false
var offset: CGFloat {
isOpen ? 0 : UIScreen.main.bounds.height / 3
}
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
Button(action: {
self.isOpen.toggle()
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 25.0)
.foregroundColor(.black)
Text("Open")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.white)
}
})
.buttonStyle(DefaultButtonStyle())
.frame(width: 300, height: 50, alignment: .center)
GeometryReader { geometry in
VStack {
Spacer()
BottomSheet()
.frame(width:geometry.size.width,
height: geometry.size.height / 3,
alignment: .center)
.background(
Color.white
)
.offset(y: offset)
.animation(.easeInOut(duration: 0.5)) .transition(.move(edge: .bottom))
} .edgesIgnoringSafeArea(.bottom)
}
}
}
}

Unwanted animation effect with .navigationBarHidden(true)

I have a simple loading view on SwiftUI.
When I am displaying this loading screen with .navigationBarHidden(true) on NavigationView.
There is an issue that animation has an unwanted effect on it.
This is my loading animation
struct LoaderThreeDot: View {
var size: CGFloat = 20
#State private var shouldAnimate = false
var body: some View {
HStack(alignment: .center) {
Circle()
.fill(Color.blue)
.scaleEffect(shouldAnimate ? 1.0 : 0.5, anchor: .center)
.animation(Animation.easeInOut(duration: 0.5).repeatForever())
.frame(width: size, height: size)
Circle()
.fill(Color.blue)
.scaleEffect(shouldAnimate ? 1.0 : 0.5, anchor: .center)
.animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.3))
.frame(width: size, height: size, alignment: .center)
Circle()
.fill(Color.blue)
.scaleEffect(shouldAnimate ? 1.0 : 0.5, anchor: .center)
.animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.6))
.frame(width: size, height: size, alignment: .center)
}
.onAppear {
self.shouldAnimate = true
}
}
}
LoadingView as follow:
struct LoadingView<Content>: View where Content: View {
let title: String
var content: () -> Content
#State var showLoader = false
var body: some View {
ZStack {
self.content()
.disabled(true)
.blur(radius: 3)
Rectangle()
.foregroundColor(Color.black.opacity(0.4))
.ignoresSafeArea()
VStack {
if showLoader {
LoaderThreeDot()
}
Text(title)
.foregroundColor(.black)
.font(.body)
.padding(.top, 10)
}
.padding(.all, 60)
.background(backgroundView)
}
.onAppear {
showLoader.toggle()
}
}
private var backgroundView: some View {
RoundedRectangle(cornerRadius: 12)
.foregroundColor(Color.white)
.shadow(radius: 10)
}
}
And simply presenting it as follow:
NavigationView {
ZStack {
LoadingView(title: "Loading...") {
Rectangle()
.foregroundColor(.red)
}
}
.navigationBarHidden(true)
}
If I remove .navigationBarHidden(true) animation looks ok.
So I am guessing that the animation effect started when the navigation bar was shown and it somehow affecting the animation after the navigation bar is hidden.
Is there any way I can avoid this?
Change your toggle on the main thered.
// Other code
.onAppear() {
DispatchQueue.main.async { //<--- Here
showLoader.toggle()
}
}
// Other code

Resources