gpt4 book ai didi

ios - 简单的 SwiftUI 模态演示和通过 @StateObject 关闭

转载 作者:行者123 更新时间:2023-12-01 16:11:18 26 4
gpt4 key购买 nike

  • Xcode 12 测试版 6 (12A8189n)
  • iPhone 11、iOS 14.0 模拟器

  • 在给定的代码示例中, CreateSomethingView 的表示有效,但是解雇它不起作用。我对使用 @StateObject 完成这项工作特别感兴趣。并避免 @State完全。
    import SwiftUI

    @main
    struct ModalPresentationApp: App {
    var body: some Scene {
    WindowGroup {
    ContentView()
    }
    }
    }

    final class ContentModel: ObservableObject {
    @Published
    var isPresenting = false
    }

    struct ContentView: View {
    @StateObject
    var contentModel = ContentModel()

    var body: some View {
    NavigationView {
    Text("ContentView")
    .toolbar {
    ToolbarItem(placement: .navigationBarTrailing) {
    Button(action: {
    contentModel.isPresenting.toggle()
    }, label: {
    Image(systemName: "plus.circle")
    })
    .sheet(isPresented: $contentModel.isPresenting) {
    CreateSomethingView(isPresented: $contentModel.isPresenting)
    }
    }
    }
    }
    }
    }

    struct CreateSomethingView: View {
    @Binding
    var isPresented: Bool

    var body: some View {
    NavigationView {
    Text("CreateSomethingView")
    .toolbar {
    ToolbarItem(placement: .navigationBarLeading) {
    Button(action: {
    isPresented = false
    }, label: {
    Image(systemName: "xmark.circle.fill")
    })
    }
    }
    }
    }
    }

    最佳答案

    只需在适当的位置附上工作表(嗯......只是根据经验,任何 *bar(s) 都不是 View 间绑定(bind)的好地方)
    这是修复。使用 Xcode 12b5/iOS 14 准备和测试

    var body: some View {
    NavigationView {
    Text("ContentView")
    .toolbar {
    ToolbarItem(placement: .navigationBarTrailing) {
    Button(action: {
    contentModel.isPresenting = true
    }, label: {
    Image(systemName: "plus.circle")
    })
    }
    }
    }
    .sheet(isPresented: $contentModel.isPresenting) {
    CreateSomethingView(isPresented: $contentModel.isPresenting)
    }
    }

    关于ios - 简单的 SwiftUI 模态演示和通过 @StateObject 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63861110/

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