100 days of swiftui: 34
https://www.hackingwithswift.com/100/swiftui/34
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
한 깃발을 선택하면 자동으로 다른 깃발은 선택되지 않았다는 속성을 지니게 했다. 특정 깃발을 선택하면 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
선택하지 않은 깃발은 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