HeeJaeEun / SwiftUI

0 stars 0 forks source link

5. Animating Views and Transitions #5

Open ddosang opened 1 year ago

ddosang commented 1 year ago

https://developer.apple.com/tutorials/swiftui/animating-views-and-transitions

ddosang commented 1 year ago

1. Overall

hikeData.json 을 읽어오기 위해 Hike 라는 struct 를 만들고,

해당 정보를 보여주기 위해서

Screenshot 2023-04-24 at 9 24 04 PM

바깥 껍데기부터 HikeView > HikeDetail > HikeGraph > GraphCapsule

으로 만듬.

애니메이션이 이 챕터의 핵심이라 해당 부분은 이미 만들어진걸 복붙해서 넣었는데, KeyPath 라는 것을 이용해서

var color: Color {
    switch path {
    case \.elevation:
        return .gray
    case \.heartRate:
        return Color(hue: 0, saturation: 0.5, brightness: 0.7)
    case \.pace:
        return Color(hue: 0.7, saturation: 0.4, brightness: 0.7)
    default:
        return .black
    }
}

\ 를 이용해서 각각의 path 를 설정할 수 있는 것 같다. 정확한 원리는 좀 더 공부 필요...

그래서 이렇게 가지고 오고,

2. 애니메이션

이미 정의된 것을 이용하면

.animation(.spring(), value: showDetail)
.animation(.easeInOut), value: showDetail)
.animation(nil, value: showDetail) // 애니메이션 없앰.

정의된 것 여러가지를 섞어서 이용하려면 직접 스타일을 만들 수 있다.

extension AnyTransition {
    static var moveAndFade: AnyTransition {
        .asymmetric(
            insertion: .move(edge: .trailing).combined(with: .opacity),
            removal: .scale.combined(with: .opacity))
    }
}

HikeDetail(hike: hike)
    .transition(.moveAndFade)

애니메이션을 넣고 싶은 view 에 (여기선 @State private var showDetail = true 에 따라서 바뀌는 View 들) 넣고 싶으면

withAnimation {
    // withAniatmion 으로 감싸면 showDetail 에 영향을 받는 녀석들 모두를 제어할 수 있다.
    showDetail.toggle()
}

애니메이션도 마찬가지로 직접 정의해서 / 기본 제공 이용 가능.

extension Animation {
    static func ripple(index: Int) -> Animation {
        Animation.spring(dampingFraction: 0.5)
            .speed(2)
            .delay(0.03 * Double(index))
    }
}

GraphCapsule(
    index: index,
    color: color,
    height: proxy.size.height,
    range: observation[keyPath: path],
    overallRange: overallRange
)
.animation(.ripple(index: index))