由网友(眼里住着星)分享简介:我正在尝试使用切换Bool值的按钮设置SwiftUI.contextMenu。切换Bool时,上下文菜单的按钮文本应该会更改。但上下文菜单不会更新。是否有强制更新上下文菜单的方法?描述该问题的示例代码:import SwiftUIstruct Item: Identifiable {let id = UUID()l...我正在尝试使用切换
Bool
值的按钮设置SwiftUI.contextMenu
。切换Bool
时,上下文菜单的按钮文本应该会更改。但上下文菜单不会更新。是否有强制更新上下文菜单的方法?
描述该问题的示例代码:
import SwiftUI
struct Item: Identifiable {
let id = UUID()
let user: String
var active: Bool
}
struct ContentView: View {
@State var items: [Item] = [
Item(user: "Daniel",active: false),
Item(user: "Jack", active: true),
Item(user: "John", active: true)
]
@State var isOn : Bool = false
var body: some View {
List {
ForEach(items) { item in
VStack {
Text("(item.user)")
HStack {
Text("Active ? ")
Text(item.active ? "YES": "NO")
}
}.contextMenu{
Button(action: {
let index = items.firstIndex{$0.user == item.user}
items[index!].active.toggle()
}) {
Text(item.active ? "Set as Active": "Set as Inactive")
}
}
}
}
}
}
推荐答案
这是SwiftUI中的一个错误,在Xcode13.2beta 2的模拟器中仍被破坏。
我设法通过在if item.active
语句的两个分支中复制列表项来解决这个问题,如下所示:
struct ContentView: View {
@State var items: [Item] = [
Item(user: "Daniel",active: false),
Item(user: "Jack", active: true),
Item(user: "John", active: true)
]
var body: some View {
List {
ForEach(items) { item in
// work around SwiftUI bug where
// context menu doesn't update
if item.active { listItem(for: item) }
else { listItem(for: item) }
}
}
}
private func listItem(for item: Item) -> some View {
VStack {
Text("(item.user)")
HStack {
Text("Active ? ")
Text(item.active ? "YES": "NO")
}
}
.contextMenu {
Button(item.active ? "Deactivate" : "Activate") {
if let index = items.firstIndex(where: { $0.id == item.id }) {
items[index].active.toggle()
}
}
}
.id(item.id)
}
}
相关推荐
最新文章