明细项不为零时显示工作表(绑定扩展)

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

我想在详细信息项不为零时显示详细信息表,而不需要额外的布尔值 @State 变量:

.sheet(isPresented: $optionalDetailItem.notNilBinding()) {
    Text("Details")
}

这是我当前的代码。如何使其适用于不可发送的项目?如果我删除可发送要求,我会收到错误

Capture of 'self' with non-sendable type 'Binding<Optional<T>>' in a '@Sendable' closure

@available(iOS 13.0, macOS 10.15, *)
public extension Binding {
    /// Careful, never set this to `true`.
    func notNilBinding<T: Sendable>() -> Binding<Bool> where Value == Optional<T> {
        Binding<Bool>(
            get: { self.wrappedValue != nil },
            set: { newValue in
                if !newValue {
                    wrappedValue = nil
                } else {
                    // In this context we cannot not know what to set `wrappedValue` to.
                    fatalError("This must not be set to `true`.")
                }
            }
        )
    }
}
swift swiftui
1个回答
0
投票

如果数据不为nil,您可以使用此方法sheet(item:onDismiss:content:)来显示sheet。

@State private var optionalDetailItem: DetailItem?

当OptionalDetailItem的值设置为非nil时,将显示sheet

.sheet(isPresented: $optionalDetailItem) {
    Text("Details")
}
© www.soinside.com 2019 - 2024. All rights reserved.