我想创建一个彩色矩形的应用程序背景。
每个矩形的颜色将由一个预定义长度的颜色数组定义。这个数组是通过重复一个作为"模式"的数组来创建的,直到达到定义的长度。
这是我到目前为止的代码:
import SwiftUI
struct ContentView: View {
private var colorArray: [Color] = [
.blue,
.green,
.red
]
@State private var newColorArray: [Color] = []
private var arrayLength: Int = 4
var body: some View {
HStack {
ForEach((0..<$newColorArray.count), id: .self) { colorI in
Rectangle()
.foregroundColor(newColorArray[colorI])
}
}
.onAppear() {
newColorArray = newArray(colorArray: colorArray, arrayLength: arrayLength)
}
}
private func newArray(colorArray: [Color], arrayLength: Int) -> [Color] {
var array: [Color] = []
var colorI = 0
for _ in 0..<arrayLength {
if !colorArray.indices.contains(colorI) {
colorI = 0
}
array.append(colorArray[colorI])
colorI = colorI + 1
}
return array
}
}
我能改变什么使它更快或使用更少的代码?
不需要创建新的数组。只需使用%
计算到colorArray
的索引。
这段代码替换了你所有的代码:
import SwiftUI
struct ContentView: View {
private var colorArray: [Color] = [
.blue,
.green,
.red
]
private var arrayLength: Int = 4
var body: some View {
HStack {
ForEach((0..<arrayLength), id: .self) { colorI in
Rectangle()
.foregroundColor(colorArray[colorI % colorArray.count])
}
}
}
}