我有一個用于選擇兩種顏色和值的演示 SwiftUI,如下所示,我想在用戶選擇不同顏色時收集顏色值。
但是它們總是鏈接相同的值,我無法將兩個“步進器”分開并將它們放入一個陣列中。
import SwiftUI
struct StepColorChange: View {
@State private var value = 0
let colors: [Color] = [.orange, .red, .gray, .blue, .green, .purple, .pink]
func incrementStep() {
value = 1
if value >= colors.count { value = 0}
}
func decrementStep() {
value -= 1
if value < 0 {
value = colors.count - 1}
}
var body: some View {
// change color with value stepper
VStack {
Stepper {
Text("Value: \(value) Color: \(colors[value].description)")
} onIncrement: {
incrementStep()
} onDecrement: {
decrementStep()
}
.padding(5)
.background(colors[value])
Stepper {
Text("Value: \(value) Color: \(colors[value].description)")
} onIncrement: {
incrementStep()
} onDecrement: {
decrementStep()
}
.padding(5)
.background(colors[value])
}
}
}
非常感謝!
uj5u.com熱心網友回復:
這不是火箭科學。嘗試這樣的事情,使用兩個值,根據每個步進器值獨立更改步進器背景顏色。
struct ContentView: View {
var body: some View {
StepColorChange()
}
}
struct StepColorChange: View {
@State private var value1 = 0
@State private var value2 = 0
let colors: [Color] = [.orange, .red, .gray, .blue, .green, .purple, .pink]
var body: some View {
VStack {
Stepper {
Text("Value: \(value1) Color: \(colors[value1].description)")
} onIncrement: {
value1 = 1
if value1 >= colors.count { value1 = 0}
} onDecrement: {
value1 -= 1
if value1 < 0 { value1 = colors.count - 1 }
}
.padding(5)
.background(colors[value1])
Stepper {
Text("Value: \(value2) Color: \(colors[value2].description)")
} onIncrement: {
value2 = 1
if value2 >= colors.count { value2 = 0}
} onDecrement: {
value2 -= 1
if value2 < 0 { value2 = colors.count - 1 }
}
.padding(5)
.background(colors[value2])
}
}
}
EDIT-1:精簡代碼
struct StepColorChange: View {
@State private var values = [0,0]
let colors: [Color] = [.orange, .red, .gray, .blue, .green, .purple, .pink]
func stepper(_ ndx: Int) -> some View {
Stepper {
Text("Value: \(values[ndx]) Color: \(colors[values[ndx]].description)")
} onIncrement: {
values[ndx] = 1
if values[ndx] >= colors.count { values[ndx] = 0}
} onDecrement: {
values[ndx] -= 1
if values[ndx] < 0 { values[ndx] = colors.count - 1}
}
.padding(5)
.background(colors[values[ndx]])
}
var body: some View {
VStack {
stepper(0)
stepper(1)
Text("stepper(0): \(values[0])")
Text("stepper(1): \(values[1])")
Text("color stepper(0): \(colors[values[0]].description)")
Text("color stepper(1): \(colors[values[1]].description)")
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531082.html
標籤:数组代码迅捷步进器