# 設定動畫

## 重點

* 用 **@State private var** 來宣告 view state，並用來控制 view 的屬性。
* 用 **ternary opeartor** (`condition ? trueValue : falseValue`) 來設定可產生動畫的屬性。
* 用 view.**animation**() 來加入動畫。
* 用 view.**onTapGesture**() 來設定「**觸控功能**」（如：改變 view state）

{% tabs %}
{% tab title="main" %}

```swift
/*
 Design+Code - SwiftUI for iOS 13
 https://designcode.io/swiftui-animations-and-states
 */

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    
    // view states
    @State private var show = false  // ⭐️ 加入 view state
    
    // view body
    var body: some View {
        ZStack {
            TitleView()
                .blur(radius: show ? 20 : 0)  // ⭐️ 由 state 控制「模糊化」程度
                .animation(.default)          // ⭐️ 加入動畫
            
            BackCard(.purple)
                .scaleEffect(0.9)
                .offset(x: 0, y: show ? -400 : -40) // ⭐️ 由 state 控制「平移」程度
                .rotationEffect(.degrees(show ? 0 : 10))  // ⭐️ 由 state 控制「旋轉」程度
                .rotation3DEffect(.degrees(10), axis: (x: 1, y: 0, z: 0))
                .blendMode(.hardLight)
                .animation(.easeInOut(duration: 0.5))     // ⭐️ 加入動畫
            
            BackCard(.pink)
                .scaleEffect(0.95)
                .offset(x: 0, y: show ? -200 : -20)
                .rotationEffect(.degrees(show ? 0 : 5))
                .rotation3DEffect(.degrees(5), axis: (x: 1, y: 0, z: 0))
                .blendMode(.hardLight)
                .animation(.easeInOut(duration: 0.3))
            
            // main card
            Card()
                .blendMode(.hardLight)
                .onTapGesture { self.show.toggle() }  // ⭐️ 由觸控來控制 state
            
            BottomCard()
                .blur(radius: show ? 20 : 0)
                .animation(.default)
            
        } // ZStack (container)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white)
    }
}

PlaygroundPage.current.setLiveView(ContentView())
```

{% endtab %}

{% tab title="截圖" %}
![Cards with animations](/files/-MG6OMY334oAHm1xj6i2)
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/master/todo/tutorials/ui-design/animations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
