在需要@Binding 的地方传递@Published 属性?
Passing @Published property where @Binding is expected?
当在 viewModel 中进行一些计算时,我想呈现模态视图。通常我需要为方法设置一些布尔绑定:
.fullScreenCover(isPresented: $isGalleryPresented) {
GalleryPickerView())
}
where isGalleryPresented,是在视图中定义的@State。然而浏览SO,我发现我可以在viewModel中有属性:
@Pulished var isGalleryPresented = false
然后做这样的事情:
.fullScreenCover(isPresented: $viewModel.isGalleryPresented) {
GalleryPickerView()
}
这很好用,虽然我不知道怎么做。 fullScreenCover
类型 isPresented: Binding<Bool>
的方法参数,我会尽我所能告诉发布者。这是如何工作的?
您的 viewModel
是 @ObservedObject
的包装 属性,它通过键路径下标提供绑定到包装的可观察对象属性。
声明对应部分如下:
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) @propertyWrapper @frozen public
struct ObservedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {
/// A wrapper of the underlying observable object that can create bindings to
/// its properties using dynamic member lookup.
@dynamicMemberLookup @frozen public struct Wrapper {
/// Returns a binding to the resulting value of a given key path.
///
/// - Parameter keyPath : A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
}
当在 viewModel 中进行一些计算时,我想呈现模态视图。通常我需要为方法设置一些布尔绑定:
.fullScreenCover(isPresented: $isGalleryPresented) {
GalleryPickerView())
}
where isGalleryPresented,是在视图中定义的@State。然而浏览SO,我发现我可以在viewModel中有属性:
@Pulished var isGalleryPresented = false
然后做这样的事情:
.fullScreenCover(isPresented: $viewModel.isGalleryPresented) {
GalleryPickerView()
}
这很好用,虽然我不知道怎么做。 fullScreenCover
类型 isPresented: Binding<Bool>
的方法参数,我会尽我所能告诉发布者。这是如何工作的?
您的 viewModel
是 @ObservedObject
的包装 属性,它通过键路径下标提供绑定到包装的可观察对象属性。
声明对应部分如下:
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) @propertyWrapper @frozen public
struct ObservedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {
/// A wrapper of the underlying observable object that can create bindings to
/// its properties using dynamic member lookup.
@dynamicMemberLookup @frozen public struct Wrapper {
/// Returns a binding to the resulting value of a given key path.
///
/// - Parameter keyPath : A key path to a specific resulting value.
///
/// - Returns: A new binding.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
}