定义数据结构体:
struct Box {
var id: Int
let title, imageUrl: String
}
定义横向滑动单元格:
import SwiftUI
struct BoxView: View {
let box: Box
var body: some View {
VStack {
Image("\(box.imageUrl)")
.resizable()
.cornerRadius(12)
.frame(width: 80, height: 80)
Text("\(box.title)")
.font(.subheadline)
.fontWeight(.bold)
}
}
}
#if DEBUG
struct BoxView_Previews: PreviewProvider {
static var previews: some View {
BoxView(box: Box(id: 4, title: "SwiftUI", imageUrl: "4"))
}
}
#endif
效果:
截屏2019-12-0716.42.59.png
定义展示页面:
import SwiftUI
struct BoxContentView: View {
let boxes: [Box] = [
Box(id: 0, title: "Autumn", imageUrl: "0"),
Box(id: 1, title: "Natural", imageUrl: "1"),
Box(id: 2, title: "Jiuzhaigou", imageUrl: "2"),
Box(id: 3, title: "Mountain", imageUrl: "3"),
Box(id: 4, title: "Lake", imageUrl: "4"),
]
var body: some View {
NavigationView {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(boxes, id: \.id) { box in
BoxView(box: box)
}
}
Spacer()
}.padding(20)
.navigationBarTitle(Text("Beautiful Scenery!"))
}
}
}
#if DEBUG
struct BoxContentView_Previews: PreviewProvider {
static var previews: some View {
BoxContentView()
}
}
#endif
最终效果:
2019-12-07 16.36.15.gif
网友评论