如何解决SwiftUI onTapGesture 仅与调用者交互
我刚刚开始研究 SwiftUI,因为它是如此不同,所以我正在尝试围绕基本概念。
在这种情况下,我将如何只为点击的圆圈更改颜色?
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
}
解决方法
好吧,我在这里看到了两个主要选项
- 制作自定义视图,例如
struct MyCircle: View {
@State var color: Color?
var body: some View {
Circle()
.foregroundColor(color)
.onTapGesture {
self.color = colors.randomElement()
}
}
}
然后整合或
- 为您的颜色使用模型
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()
}
}
}
}
像这样的状态最好在它自己的类中,它应该作为 ObservedObject
插入。
您创建了一个 View
,它具有“Rows”个别属性
import SwiftUI
struct SampleColorChangeView: View {
//If the options are fixed no need to keep an eye on them
//You can move this down to the Row if you don't need to have them available here
let colors: [Color] = [.red,.blue,.gray,.yellow,.orange]
@State var count: Int = 10
var body: some View {
VStack{
ForEach(1...count,id: \.self) { _ in
RowView(colors: colors)
}
}
}
}
//Create a row View to observe individual objects
//You will do this with anything that you want to Observe independently
struct RowView: View {
let colors: [Color]
//@State observes changes so the View is updated
@State var color: Color = .blue
//This kind of works like the colors do you want one for each or a shared for all. Does the parent need access? You can move it up or keep it here
@State var stepperValue: CGFloat = 0
//The only change here is the reference to the individual Color
var body: some View {
Circle()
//You set the individual color here
.foregroundColor(color).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
color = colors.randomElement()!
print("Tapped")
})
.animation(.default) // Animate the change in position
//If you want to set a random color to start vs just having them all be the same Color you can do something like this
.onAppear(){
color = colors.randomElement()!
}
}
}
struct SampleColorChangeView_Previews: PreviewProvider {
static var previews: some View {
SampleColorChangeView()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。