In one ColorOptions view I have 7 colors with different opacities, and picker to change those colors for Circle() in another view, but have problem, with ".fill" because when im trying to fill color with the same color as index then when app launches getting error for index out of range, another line of code (GPT provide) with default color, but then problem is when app launches, launches with the same colorIndex but default color, when need launch same color which which app closes, so question, how to launch app withe the same fill Circle() color as when app closes? Becouse in print statements possible see selectedColorIndex same when app starts but color going to "0" , ".red.opacity(0.3)" and with line ".fill(selectedColors[selectedColorIndex])" getting error where and index and selectedC olor supose to be the same.
ColorOptions View:
@Binding var selectedColorIndex: Int
@Binding var selectedColors: [Color]
@State private var colorOptions: [(name: String, colors: [Color])] = [
("Red", [
.red.opacity(0.1),
.red.opacity(0.3),
.red.opacity(0.2),
.red.opacity(0.1),
.red.opacity(0.3),
.red.opacity(0.1),
.red.opacity(0.3),
.red.opacity(0.1),
.red.opacity(0.1),
.red.opacity(0.3),
.red.opacity(0.1),
.red.opacity(0.2),
.red.opacity(0.1),
.red.opacity(0.2),
.red.opacity(0.3),
]),
("White", [
.white.opacity(0.1),
.white.opacity(0.3),
VStack {
Picker("Select a color", selection: $selectedColorIndex) {
ForEach(0..<colorOptions.count, id: \.self) { index in
Text(colorOptions[index].name)
.foregroundColor(index == selectedColorIndex ? .primary : .secondary)
.tag(index)
}
}
.pickerStyle(.wheel)
.onChange(of: selectedColorIndex) { newValue in
if newValue < colorOptions.count {
selectedColors = colorOptions[newValue].colors
print("Selected color index changed to: \(newValue)")
print("Number of selected color index: \(selectedColorIndex)")
userDefaultsManager.saveSelectedColorIndex(newValue)
userDefaultsManager.saveSelectedColors(selectedColors)
isSheetPresented = false
}
}
}
Another view:
@Binding var selectedColors: [Color]
@Binding var selectedColorIndex: Int
var body: some View {
ZStack {
ForEach(0..<15, id: \.self) { index in
Circle()
.fill(selectedColors[selectedColorIndex])
// .fill(selectedColorIndex < selectedColors.count ? selectedColors[selectedColorIndex] : .red.opacity(0.3))
.frame(width: circleSizes[index], height: circleSizes[index])
.blur(radius: 45)
.position(randomPosition(index: index))
.animation(
Animation.linear(duration: 9)
.repeatForever(autoreverses: true)
)
}
}
}
Tried use ".fill(selectedColorIndex < selectedColors.count ? selectedColors[selectedColorIndex] : .red.opacity(0.3))" GPT provided line but this line with default color which when opens app Circle() starts with the same color, but in print statement writes Color index different, trying without the default color for user no need to change every time when app launches.