我有带有自定义数据的JSON文件。 目标是要在PostCard()
的{{1}}中使用此数据。但是在evetytime时,我尝试在内部使用ForEach(){}
,但在VStack 中收到此错误,无法推断复杂的闭包返回类型;添加显式类型以消除歧义。
我的JSON转换器功能如下:
user
自定义数据类型:
let userResponse: [UserResponse] = load("users.json")
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
我在子视图中对其进行了初始化:
struct UserResponse: Hashable, Codable, Identifiable {
public var id: Int
public var username: String
public var avatar: String
public var postOne: String
public var postTwo: String
public var postThree: String
public var postFour: String
public var story: String
public var likes: Int
public var commentNumber: Int
public var location: String
public var comment: String
public var name: String
public var followers: Int
public var following: Int
public var postNumbers: Int
public var bio: String
public var locationPic: String
}
var user : UserResponse
我的ZStack{
VStack{
ForEach(userResponse){user in
HStack(alignment: .center, spacing: 5){
PostCard(user: user)
.padding(EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 0))
PostCard(user: user)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
}.shadow(color: Color("greySec"), radius: 3, x: 0, y: 0)
}
}.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarHidden(true)
}
结构如下:
PostCard
var user : UserResponse
问题:是否有人知道如何在VStack(spacing: 10){
HStack(spacing: 5){
VStack(spacing: 10){
Image(user.postOne)
.resizable().frame(height: 290)
HStack{
Text(user.comment)
.font(.system(size: 12, weight: .medium))
.padding(EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5))
}
}
.background(Color("whiteAndBlack"))
.cornerRadius(5)
.foregroundColor(.black)
}
}
内使用JSON数据?我的目标是为每个明信片使用各种JSON数据创建此视图。