无法将类型“ Binding <Int>”的值转换为预期的参数类型“ Binding <_>”

我正在尝试使用以下代码在SwiftUI中创建TabView

@State var selection = 0

var body: some View {
    TabView(selection: $selection) {
        DataGridPage(type: "media").tabItem {
            Image(systemName: "photo.on.rectangle")
                .imageScale(.large)
                .foregroundColor(.yellow)
        }
        .tag(1)

        DataGridPage(type: "files").tabItem {
            Image(systemName: "doc.on.doc")
                .imageScale(.large)
                .foregroundColor(.yellow)
        }
        .tag(2)
    }
}

但是我收到错误Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<_>'。我看到变量selection是整数,这是正确的类型,但是由于某些原因,警告仍然存在。

lvhg1985 回答:无法将类型“ Binding <Int>”的值转换为预期的参数类型“ Binding <_>”

我发现了问题所在。事实是,即使闭包中存在某些错误,TabView也会显示此错误。因此,创建TabView的代码是正确的,但问题是我初始化DataGridPage的方式。我在type内将属性data的名称更改为DataGridPage,但是在这里我仍在使用type属性。我修复了它,但它停止向我显示警告。

我认为SwiftUI是一个新框架,在调试方面还有很多改进。我希望它会在将来成熟,并且我们能够指出确切的错误,而不是这个模糊的声明。

新代码现在如下所示:

@State var selection = 0

var body: some View {
    TabView(selection: $selection) {
        DataGridPage(data: "media").tabItem {
            Image(systemName: "photo.on.rectangle")
                .imageScale(.large)
                .foregroundColor(.yellow)
        }
        .tag(1)

        DataGridPage(data: "files").tabItem {
            Image(systemName: "doc.on.doc")
                .imageScale(.large)
                .foregroundColor(.yellow)
        }
        .tag(2)
    }
}

希望它可以帮助面临类似问题的人。

本文链接:https://www.f2er.com/3154554.html

大家都在问