I am a beginner at SwiftUI.
I created a struct to save some text and the detail information link page. like this:
struct First: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: View //link to customised page
the property link will save the View I have created as Page1.swift, Page2.swift, Page2.swift...
How to define the link type in the struct First?
Thanks a lot.
CodePudding user response:
I use something similar in my code. I use AnyView (not recommended by Apple)
struct First: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: AnyView
}
and when I call the view, I do
AnyView(MyView())
OR (thanks Timmy)
struct First<Content: View>: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: Content
}
and call the view with
First(title: "xxx", icon: "xxx", link: View1())
The second method does not work if it is included in a static property.
Error : Static stored properties not supported in generic types
CodePudding user response:
- You can use
AnyView(not recommended):
struct First: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: AnyView
- Using generics:
struct First<Content: View>: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: Content
- You could instead create an enum:
enum First: Int, Identifiable {
//your cases
var id: Int {
return rawValue
}
var title: String {
switch self {
//cases
}
}
var icon: String {
switch self {
//cases
}
}
var link: some View {
switch self {
//cases
}
}
}
CodePudding user response:
Thanks @Timmy, Thanks @dibs,
I use this define and the program run with code
First(title: "xxx", icon: "xxx", link: AnyView(View1())),
First(title: "xxx", icon: "xxx", link: AnyView(View2())),
as below:
struct First: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: AnyView
}
but the second way, there is some wrong when I call views by below way:
First(title: "xxx", icon: "xxx", link: View1()),
First(title: "xxx", icon: "xxx", link: View2()),
I try to use the way to call view by link: AnyView(View1()), link: AnyView(View2()), it success.
struct First<Content: View>: Identifiable {
let title: String
let icon: String
let id = UUID()
let link: Content
Thanks the help from @Timmy, @dibs
