struct ContentView: View {
@State private var color: Color = .black
private var colors: [Color] = [.black, .red, .green, .yellow, .cyan]
var body: some View {
Button() {
// pick one of the below options and comment out the other.
// this gets a random color each time
color = Color.random()
// this gets a random color from the pre set colors array above.
// you could also keep track of index and loop over the colors in order and start over if needed.
// if let randomColor = colors.randomElement() {
// color = randomColor
// }
} label: {
Rectangle().fill(color)
}
.frame(width: 60, height: 30)
}
}
public extension Color {
static func random() -> Color {
Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
opacity: 1
)
}
}
3条答案
按热度按时间nwlls2ji1#
下面的例子如何(单击在两种颜色之间切换):
qvtsj1bj2#
你有一套颜色,你必须使用或你想使用一个随机的颜色对每一次点击?
这里有两个选项,只是取消注解你想使用的任何一个:
一个使用设置颜色的数组,另一个使用Color扩展每次获得一个随机颜色:
up9lanfz3#
你可以使用
ButtonStyle
isPressed
来实现。