如何解决在 ForEach 中更改刚刚单击的对象的值
当我单击顶部的单元格时,我只希望该对象上出现“已单击”文本。为什么我会在其他单元格上看到此文本?我该如何解决这个问题?
CellView
struct CellView: View {
@Binding var text: String
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 30)
.foregroundColor(Color(UIColor.secondarySystemBackground))
.frame(width: 300,height: 100)
Text(text)
}
}
}
内容视图
struct ContentView: View {
@State var text: String = ""
var body: some View {
vstack {
ForEach(0 ..< 5) { item in
Button(action: {
self.text = "Clicked"
}) {
CellView(text: $text)
}
}
}
}
}
解决方法
您会在其他单元格上看到文本,因为这是您在所有单元格中显示的内容。尝试这样的事情:
struct ContentView: View {
@State var text: String = ""
@State var selection: Int?
var body: some View {
VStack {
ForEach(0 ..< 5) { item in
Button(action: {
selection = item
text = "Clicked"
}) {
if selection == item {
CellView(text: $text)
} else {
CellView(text: .constant(""))
}
}
}
}
}
}
,
您正在更新用于所有单元格的单个字符串 text
。当它更改时,所有单元格都将使用该单个字符串进行更新。这里有几个选项:
你可以让 cell 负责存储和更新它自己的状态:
struct CellView: View {
@State var text: String = ""
var body: some View {
Button(action: {
self.text = "Clicked"
}) {
ZStack {
RoundedRectangle(cornerRadius: 30)
.foregroundColor(Color(UIColor.secondarySystemBackground))
.frame(width: 300,height: 100)
Text(text)
}
}
}
}
struct CellClickContentView: View {
var body: some View {
VStack {
ForEach(0 ..< 5) { item in
CellView()
}
}
}
}
或者您可以以某种方式在父视图中存储每个单元格的状态:
class CellState: ObservableObject,Identifiable {
var id = UUID()
@Published var text = ""
}
struct CellView: View {
@ObservedObject var state: CellState
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 30)
.foregroundColor(Color(UIColor.secondarySystemBackground))
.frame(width: 300,height: 100)
Text(state.text)
}
}
}
struct CellClickContentView: View {
@State var states: [CellState] = (0..<5).map { _ in CellState() }
var body: some View {
VStack {
ForEach(states) { state in
Button(action: {
state.text = "Clicked"
}) {
CellView(state: state)
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。