gpt4 book ai didi

swift - 如何在 SwiftUI 中检查 EditButton/EditMode 状态

转载 作者:行者123 更新时间:2023-12-01 23:20:51 24 4
gpt4 key购买 nike

我有以下测试代码。但是当点击编辑按钮时,文本不会改变。我找不到任何相关信息。如何检查/控制editButton/editMode状态变化?

struct TestView: View {
@State private var list = [1,2,3,4,5]
@State private var selection = Set<Int>()
@Environment(\.editMode) var mode

var body: some View {
NavigationView {
List(selection: $selection) {
ForEach(list, id: \.self) { item in
Text("\(item)")
}
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
EditButton()
}
ToolbarItem(placement: .navigationBarTrailing) {
if mode?.wrappedValue.isEditing ?? false {
Text("Editing")
} else {
Text("Not Editing")
}
}
}
}
}
}

最佳答案

您可以通过将 .environment 设置为 @State 模式来实现这一点。

struct TestView: View {
@State private var list = [1,2,3,4,5]
@State private var selection = Set<Int>()
@State var mode: EditMode = .inactive //< -- Here

var body: some View {
NavigationView {
List(selection: $selection) {
ForEach(list, id: \.self) { item in
Text("\(item)")
}
}

.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
EditButton()
}
ToolbarItem(placement: .navigationBarTrailing) {
Text(mode == .active ? "Editing" : "Not Editing")
}
}.environment(\.editMode, $mode) //< -- Here
}
}
}

关于swift - 如何在 SwiftUI 中检查 EditButton/EditMode 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68104918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com