UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 46, Challenge: Animated arrow solution

Forums > 100 Days of SwiftUI

This is my solution to the arrow challenge, and its animation.

The arrow shape is easy in itself, but when I stroked it went outside its bounds. So I needed .strokeBorder() and for that I made the ArrowView struct Insettable via a var insetAmount. This makes the arrow slightly smaller when I increase the lineWidth of the stroke (in my main struct, DrawingView).

Next challenge was to animate the change of lineWidth. I put this under withAnimation, and this indeed animates the change of lineWidth. But the change of the arrow size, governed by insetAmount, was still sudden. So I put insetAmount under animatableData.

The difficulty for me was to realize that lineWidth and insetAmount both need to be animated, and that this must be done in different manners.

This solution does not look too complicated, but I would be interested in any possible improvements or alternatives.

import SwiftUI

struct Arrow: InsettableShape {
    var insetAmount = 0.0

    var animatableData: Double {
        get { insetAmount }
        set { insetAmount = newValue}
    }

    func path(in rect: CGRect) -> Path {
        var path = Path()

        path.move(to: CGPoint(x: rect.midX, y: rect.height - insetAmount))
        path.addLine(to: CGPoint(x: rect.midX, y: insetAmount))
        path.addLine(to: CGPoint(x: insetAmount, y: rect.height * 0.33))
        path.move(to: CGPoint(x: rect.midX, y: insetAmount))
        path.addLine(to: CGPoint(x: rect.width - insetAmount, y: rect.height * 0.33))

        return path
    }

    func inset(by amount: CGFloat) -> some InsettableShape {
        var arrow = self
        arrow.insetAmount += amount
        return arrow
    }
}

struct DrawingView: View {
    @State private var lineWidth = 1.0

    var body: some View {

        VStack {
            Arrow()
                .strokeBorder(.blue, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round))

            Spacer()

            Button("Change line width") {
                withAnimation(.easeInOut(duration: 1)) {
                    lineWidth = Double.random(in: 1...20)
                }
            }
        }
    }
}

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.