还存在另一个不太严重的错误:用户需要点击编辑按钮两次才能激活编辑模式。
我的解决方法是当应用程序变为非活动状态时从工具栏中删除 EditButton,并在应用程序再次变为活动状态时再次显示它:
var body: some Scene {
WindowGroup {
MainView()
.onChange(of: scenePhase) { scenePhase in
switch scenePhase {
case .background:
print(".background")
case .inactive:
state.showToolbarItems = false
state.editMode = .inactive
case .active:
state.showToolbarItems = true
@unknown default:
print("unknown scenePhase")
fatalError()
}
}
}
}
在定义工具栏项的视图中,将其包含在 if 语句中:
.toolbar {
if state.showToolbarItems {
ToolbarItemGroup(placement: .primaryAction) {
CustomEditButton(editMode: $state.editMode)
}
}
}
关于另一个错误 - 需要点击按钮两次才能激活编辑模式 - 我通过使用自定义编辑模式按钮解决了该错误:
struct CustomEditButton: View {
@Binding var editMode: EditMode
var cleanUpAction: () -> Void = {}
var prepareEditMode: () -> Void = {}
var body: some View {
Button {
withAnimation {
if editMode == .active {
editMode = .inactive
cleanUpAction()
} else {
editMode = .active
prepareEditMode()
}
}
} label: {
if editMode == .active {
Text("Done").bold()
} else {
Text("Edit")
}
}
}
这是上面引用的状态类,我在视图中用作 ObservedObject :
class AppState: ObservableObject {
static var shared = AppState()
init() { }
@Published var editMode: EditMode = .inactive
@Published var showToolbarItems: Bool = true
}