swift - SwiftUI onTapGesture interact with caller only
问题描述
I've just started looking into SwiftUI and since it's so different I'm trying to wrap my head around basic concepts.
In this scenario, how would I go about changing the color only for the circle tapped?
ForEach(1...count, id: \.self) { _ in
Circle()
.foregroundColor(colors.randomElement()).opacity(0.2)
.frame(width: .random(in: 10...100), height: .random(in: 10...100))
.position(x: .random(in: self.stepperValue...400),
y: .random(in: self.stepperValue...400))
.saturation(2.0)
.onTapGesture(count: 1, perform: {
// Change color of circle that was tapped
print("Tapped")
})
.animation(.default) // Animate the change in position
}
解决方案
Well there are two main options I see here
- Make a custom view like
struct MyCircle: View {
@State var color: Color?
var body: some View {
Circle()
.foregroundColor(color)
.onTapGesture {
self.color = colors.randomElement()
}
}
}
and then integrate that or
- Use a model for your color
struct MyView: View {
@State var colors = allColors.indices.compactMap { _ in allColors.randomElement() }
var body: some View {
ForEach(colors.indices) { index in
Circle()
.foregroundColor(colors[index])
.onTapGesture {
colors[index] = allColors.randomElement()
}
}
}
}
A state like this should preferably be in its own class which should be inserted as ObservedObject
.
推荐阅读
- c# - 在 EF Core 中,我应该使用数据库查询来加入一对多表还是在 c# 中通过 efcore 手动加入?
- rust - Rust SERDE 是否需要字段顺序?
- linux - 当我尝试在 Ubuntu(Linux)中下载 expo 时出现“找不到命令”
- java - 无法从字符串单元格访问单元格的数值
- javascript - 如何在Vue中显示选定值的信息
- git - 9 月 30 日 LetsEncrypt 证书到期时,Ubuntu 20.04 上的“git”是否损坏?
- blazor - Identity->Account Manage as Razor 组件,一致的 UI
- css - CSS:保持由border-radius创建的子弹的纵横比
- java - 从包含不同类对象的列表的每个对象中检索实例变量的特定值
- google-bigquery - 如何在 BigQuery 中将字符串化数组字段转换为长整数列而没有重复字段?