ios 如何将通用SwiftUI视图添加到另一个视图?

vxqlmq5t  于 12个月前  发布在  iOS
关注(0)|答案(2)|浏览(203)

当尝试使用泛型类型初始化/添加视图到另一个SwiftUI视图时,我得到错误Type 'T' has no member 'init'。如何解决这个问题?
我想问题是,View只是一个协议,只需要一个body属性,仅此而已。但是可以使用什么类型呢?

简单示例:

尝试使用TrippleView<T: View>,它应该创建/显示三个T类型的视图。添加视图(RedRectViewBlueCircleView)没有问题。将这些视图作为泛型参数传递失败:

struct SomeView: View {
    var body: some View {
        TrippleView<RedRectView>()
        TrippleView<BlueCircleView>()
    }
}

struct TrippleView<T: View>: View {
    var body: some View {
        VStack {
            // Does NOT work: Type 'T' has no member 'init'
            T()
            T()
            T()
            
            // Works fine
            // RedRectView()
            // BlueCircleView()
            // RedRectView()
        }
    }
}

struct RedRectView: View {...}
struct BlueCircleView: View {...}

字符串

编辑:

当然,TrippleView只是一个例子,我想像使用任何其他泛型类型一样使用泛型视图:在不同的场景中使用一个公共的基础“类型”。
例如,两个版本的列表视图使用通用的CellView以两种不同的样式/布局显示相同的数据。

fivyi3re

fivyi3re1#

你需要在你的结构中有一个ViewBuilder来初始化视图。这里有一个例子,

接受泛型视图并返回视图的结构。

struct TripleView<T: View>: View {
// simple example that takes in one parameter.
var someView: T

init(@ViewBuilder someView: () -> T) {
    self.someView = someView()
}

var body: some View {
    // You can modify your viewes here. 
    someView
        .foregroundColor(.red)
    someView
        .foregroundColor(.blue)
    someView
        .foregroundColor(.green)
    }
}

字符串
或者你可以接受多个参数

struct TripleViewsWithParam<T1: View, T2: View, T3: View>: View {
// you can take as many parameters as you want.
var someView1: T1
var someView2: T2
var someView3: T3

init(@ViewBuilder someView1: () -> T1, @ViewBuilder someView2: () -> T2, @ViewBuilder someView3: () -> T3) {
    self.someView1 = someView1()
    self.someView2 = someView2()
    self.someView3 = someView3()
}

var body: some View {
    VStack {
        someView1
        someView2
        someView3
    }
}
}

在主视图中调用struct

struct SomeView: View {
var body: some View {
    VStack{
        TripleView {
            Text("Triple View Example")
        }
        TripleViewsWithParam(
            someView1: {
                Text("View 1")
            }, someView2: {
                Text("View 2")
            }, someView3: {
                Text("View 3")
            }
        )
    }

}
}


的数据

2j4z5cfb

2j4z5cfb2#

2024年1月更新

现在有一个视图构建器的属性 Package 器。所以你不需要编写初始化器。

@ViewBuilder let viewContent: ViewContent

字符串

  • 示例 *
import SwiftUI

struct ExampleView<ViewContent: View>: View {

@ViewBuilder let content: ViewContent

    var body: some View {
        VStack {
            Text("Hello World")
            
            content
        }
    }
}

#Preview {
    ExampleView {
        Text("Hello World")
    }
}

  • 用途 *
import SwiftUI

@main
struct ExampleApp: App {
    var body: some Scene {
        WindowGroup {
            ExampleView {
                Text("Hello World")
            }
        }
    }
}

相关问题