34: Animations, part 3

그루두·2024년 5월 21일
0

100 days of SwiftUI

목록 보기
43/108

100 days of swiftui: 34
https://www.hackingwithswift.com/100/swiftui/34

challenge

  1. When you tap a flag, make it spin around 360 degrees on the Y axis.
  2. Make the other two buttons fade out to 25% opacity.
  3. Add a third effect of your choosing to the two flags the user didn’t choose – maybe make them scale down? Or flip in a different direction? Experiment!

solution

1. 깃발을 누르면 y축으로 360도 돌아가는 애니메이션 적용하기

struct FlagButton: View {
    let flagName: String
    @State private var rotationAnimationAmount = 0.0
    var body: some View {
        Button(flagName) {
            rotationAnimationAmount += 360
        }
        .font(.system(size: 100))
        .rotation3DEffect(
            .degrees(rotationAnimationAmount), axis: (x: 0.0, y: 1.0, z: 0.0)
        )
        .animation(.bouncy(duration: 0.5, extraBounce: 0.3), value: rotationAnimationAmount)
    }
}

코드 파일
https://github.com/treesofgroo/Ios-Animations/commit/7db24c16346561bab4d31fdb4d86cff75c12d2bb

2. 선택하지 않은 두 개의 깃발을 투명도를 25%로 줄이기

한 깃발을 선택하면 자동으로 다른 깃발은 선택되지 않았다는 속성을 지니게 했다. 특정 깃발을 선택하면 selectedFlag에 해당 깃발의 text로 설정하고, FlagButton 내의 isSelected 속성은 selectedFlag에 따라 true/false 값을 변경했다.

struct ContentView: View {
    @State private var rotationAnimationAmount = 0.0
    @State private var selectedFlag: String = ""
    var body: some View {
        HStack {
            FlagButton(flagName: "🇰🇷", selectedFlag: $selectedFlag)
            FlagButton(flagName: "🇩🇪", selectedFlag: $selectedFlag)
            FlagButton(flagName: "🇦🇺", selectedFlag: $selectedFlag)
        }
        .padding()
    }
}

struct FlagButton: View {
    let flagName: String
    @Binding var selectedFlag: String
    @State private var rotationAnimationAmount = 0.0
    var isSelected: Bool {
        flagName == selectedFlag
    }
    var body: some View {
        Button(flagName) {
            rotationAnimationAmount += 360
            selectedFlag = flagName
        }
        .font(.system(size: 100))
        .rotation3DEffect(
            .degrees(rotationAnimationAmount), axis: (x: 0.0, y: 1.0, z: 0.0)
        )
        .animation(.bouncy(duration: 0.5, extraBounce: 0.3), value: rotationAnimationAmount)
        .opacity(isSelected ? 1 : 0.25)
        .animation(.smooth, value: isSelected)
    }
}

코드 파일
https://github.com/treesofgroo/Ios-Animations/commit/c24ff3c940d648b1e5558d53d8b211ff63ab4e62

3. 선택되지 않은 깃발에 애니메이션 추가하기

선택하지 않은 깃발은 offset을 추가하고 크기를 줄여 뒤로 물러나는 듯한 효과를 주었다.

		// ... 
        .offset(isSelected ? .zero : CGSize(width: 0.0, height: 15))
        .scaleEffect(isSelected ? 1 : 0.7)
        .animation(.smooth, value: isSelected)
        // ... 

코드 파일
https://github.com/treesofgroo/Ios-Animations/commit/451db8627d0eeeadafe88288943f322057c619c2

profile
계속 해보자

0개의 댓글

관련 채용 정보