gpt4 book ai didi

SwiftUI:无法推断通用参数 'Subject'

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:44 27 4
gpt4 key购买 nike

我使用 SwiftUI 构建了一个 LoadingView,用于在我从 API 获取远程数据时显示我的应用程序中的一些加载内容。我正在使用 Xcode 版本 11.0 beta 5。

这是LoadingView:

struct LoadingView<Content>: View where Content: View {

@Binding var isShowing: Bool
var content: () -> Content

var body: some View {

GeometryReader { geometry in

ZStack(alignment: .center) {

self.content()
.disabled(self.isShowing)
.blur(radius: self.isShowing ? 3 : 0)

VStack {
Text("Loading...")
ActivityIndicator(isAnimating: .constant(true), style: .large)
}
.frame(width: geometry.size.width / 2,
height: geometry.size.height / 5)
.background(Color.white)
.foregroundColor(Color.primary)
.cornerRadius(5)
.opacity(self.isShowing ? 1 : 0)
}
}
}
}

这是我的数据存储。它被声明为 ObservableObject 并且具有多个 @Published 属性。它还从 API 进行一些远程获取:

class CharacterStore: ObservableObject {

@Published private(set) var isLoading = false


// Fetches some stuff from a remote api
func fetch() {

self.isLoading = true

myService.getCharacters { (result) in
DispatchQueue.main.async {
self.isLoading = false
}
}
}
}

最后,这是我要显示我的 LoadingView 的 View ,其中包含 ContentView 的内容。当然,我在显示此 View 之前设置了 @EnvironmentObject

struct ContentView: View {

@EnvironmentObject var charStore: CharacterStore

var body: some View {

LoadingView(isShowing: self.$charStore.isLoading) { // Here I get the error

// Show some Content here
Text("")
}
}
}

问题是我想将 self.$charStore.isLoading 绑定(bind)到 LoadingView。在这一行中,我收到以下错误:

Generic parameter 'Subject' could not be inferred

我尝试了几种方法,但这些方法都不起作用。顺便说一句:如果我在 ContentView 中使用 @State 属性,它就可以像这样正常工作:

struct ContentView: View {

@EnvironmentObject var charStore: CharacterStore

@State var loads: Bool = false

var body: some View {

LoadingView(isShowing: self.$loads) { // Here I get no error

// Show some Content here
Text("")
}
}
}

我错过了什么吗?如果您需要更多信息,请告诉我,如果需要,我可以提供更多内容。

感谢您的帮助!

最佳答案

因为您的 LoadingView 不会修改 .isLoading,所以您不需要将其作为绑定(bind)传递:

LoadingView(isShowing: self.$charStore.isLoading)

相反,删除 LoadingView 中的 @Binding:

struct LoadingView<Content>: View where Content: View {

var isShowing: Bool
...

并像这样创建它(删除美元符号):

LoadingView(isShowing: self.charStore.isLoading) { ... }

相反,如果你坚持传递一个绑定(bind),那么你需要移除private(set) from:

@Published private(set) var isLoading = false

关于SwiftUI:无法推断通用参数 'Subject',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424157/

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