当应用程序移至后台时,SwiftUI NavigationSplitView 会丢失工具栏按钮 - iOS 17 / Xcode 15.0

问题描述 投票:0回答:1

@main struct EditModeMoveToBackgroundApp: App { var body: some Scene { WindowGroup { NavigationSplitView(columnVisibility: .constant(.all)) { ContentView() } detail: { Text("Detail View") } } } } struct ItemStore: Identifiable, Hashable { var id = UUID() var name: String } struct ContentView: View { var itemArray = ["Mountain", "River", "Village"].map { ItemStore(name: $0) } @Environment(\.editMode) private var editMode @State var selection: Set<ItemStore.ID> = [] var body: some View { List(selection: $selection) { ForEach(itemArray) { item in Text(item.name) } } .toolbar { EditButton() } } }

这是一个严重的错误,因为它将用户锁定在编辑模式下,只能通过再次冷启动应用程序来退出。
有人知道解决方案/解决方法吗?

还存在另一个不太严重的错误:用户需要点击编辑按钮两次才能激活编辑模式。

我的解决方法是当应用程序变为非活动状态时从工具栏中删除 EditButton,并在应用程序再次变为活动状态时再次显示它:
ios swiftui toolbar
1个回答
0
投票
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
}


© www.soinside.com 2019 - 2024. All rights reserved.