如何根據需要為單個按鈕添加修飾符?
我有一個ForEach回圈在一系列范圍內運行,0..<5我需要根據它們的狀態添加一個.rotation3DEffect點擊按鈕的影片和另一個.opacity未點擊按鈕的影片。
注意:我可以觀察按鈕動作中的任何狀態值,然后將其更改為具有影片,但由于修飾符應用于回圈
Button內的自身ForEach,因此我將影片應用于 foreach 中的每個按鈕。
@State private var rotationDegree = 0.0
@State private var selectedNum = 0
@State private var correctAnswer = 0 // comes from saved data
var body: some View {
ForEach(0..<5) { num in // image as a button, loops through their prefix name
Button {
selectedNum = (num == correctAnswer) ? num : 0
withAnimation {
// once clicked, will animate all 5 buttons, need only this clicked button to animate.
if (num == correctAnswer) {
rotationDegree = 360
}
}
} label: {
Image("imageName\(num)")
}
.rotation3DEffect((.degrees((selectedNum == correctAnswer) ? rotationDegree : 0.0)), axis: (x: 0, y: (selectedNum == correctAnswer) ? 1 : 0, z: 0)) // animation I want to add to a specific button
}
}
uj5u.com熱心網友回復:
import SwiftUI
struct AnimatedListView: View {
var body: some View {
VStack{
ForEach(0..<5) { num in
//The content of the ForEach goes into its own View
AnimatedButtonView(num: num)
}
}
}
}
struct AnimatedButtonView: View {
//This creates an @State for each element of the ForEach
@State private var rotationDegree = 0.0
//Pass the loops data as a parameter
let num: Int
var body: some View {
Button {
withAnimation {
rotationDegree = 360
}
} label: {
Image(systemName: "person")
Text(num.description)
}
.rotation3DEffect((.degrees(rotationDegree)), axis: (x: 0, y: 1, z: 0))
}
}
struct AnimatedListView_Previews: PreviewProvider {
static var previews: some View {
AnimatedListView()
}
}
uj5u.com熱心網友回復:
嘗試將其添加到您的視圖中。
@State var selectedNum: Int = 0
然后將您的按鈕更改為如下所示。
Button {
selectedNum = num
withAnimation {
rotationDegree = 360
}
} label: {
Image("imageName\(num)")
}
// Check if the selected button is equal to the num
.rotation3DEffect((.degrees(selectedNum == num ? rotationDegree : 0.0)), axis: (x: 0, y: 1, z: 0))
不確定rotation3DEffect 是如何作業的。但這是另一個例子
.background(selectedNum == num ? .red : .blue)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370286.html
