问题
Excuse the length of this question, but I have a swift UI that has words displayed in concentric circles. I want to be able to press the right and left button and have the words rotate clockwise and counterclockwise respectively. My withAnimation{}
button function works as long as the text is not in a ForEach loop. Is there a way to change state variables that are in a ForEach loop? In my case animate a rotation of a view that is within a ForEach. In this case I want to use the slider to pick which level I am rotating.
code: import SwiftUI
struct ContentView: View {
@State var circle = Circle()
@State var platform: Float = 0.0
@State var platformBool = false
@State var colors = [Color.red, Color.black, Color.orange, Color.white, Color.green, Color.gray, Color.blue]
@State var colorOne = Color.red
@State var colorTwo = Color.black
@State var levelWords = [["A","B","O","R","T","S"], ["B","E","N","I","G","N"], ["A","B","O","R","T","S"], ["B","E","N","I","G","N"], ["A","B","O","R","T","S"], ["B","E","N","I","G","N"]]
@State var angle = Double(0)
@State var angles = [Double(0), Double(0), Double(0), Double(0), Double(0), Double(0),]
@State var radius: CGFloat = 175.0
var body: some View {
let rows = (self.levelWords[0].count)
let columns = (self.levelWords.count)
let radiiStep: CGFloat = self.radius / CGFloat(self.levelWords[0].count + 1)
let degreeStep = Double(360 / self.levelWords[0].count)
func floatValue(one: CGFloat, two: CGFloat, three: Int) -> CGFloat {
let float = CGFloat(three)
let floatValue = one - two * float
return -floatValue
}
func degreeValue(one: Double, two: Double, three: Double) -> Double {
let value = -(one + two * three)
return value
}
return
VStack {
ZStack{
self.circle
.fill(RadialGradient(gradient: Gradient(colors: [Color.black, Color.blue]), center: .center, startRadius: 30, endRadius: 200))
ForEach(0..<columns) { column in
ForEach(0..<rows) { row in
Text("\(self.levelWords[column][row])")
.rotationEffect(.degrees(degreeValue(one: self.angles[column], two: Double(row), three: degreeStep)))
.offset(y: floatValue(one: self.radius, two: radiiStep, three: column))
.rotationEffect(.degrees(self.angles[column] + Double(row) * degreeStep))
.foregroundColor(Color.white)
}
}
Text("rot")
.rotationEffect(.degrees(self.angles[Int(self.platform)]))
.foregroundColor(Color.white)
}
Spacer()
HStack{
Spacer()
Button("Left") {
withAnimation{
self.angles[Int(self.platform)] -= Double(360 / self.levelWords[0].count)
print(self.angles[Int(self.platform)])
}
}
Spacer()
Button("Right") {
withAnimation{
self.angle += Double(360 / self.levelWords[0].count)
print("rotated")
}
}
Spacer()
}
Slider(value: $platform, in: 0...5)
.padding()
Text("platform: \(Int(platform))")
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
来源:https://stackoverflow.com/questions/61472189/swift-ui-rotation-inside-foreach-loop