After the delays of the previous three days, it’s back to Learning New Stuff.
Lesson 5 sees us creating the models required for parsing the JSON data we receive from Yelp.
struct Business: Decodable, Identifiable {
var id: String?
var alias: String?
var name: String?
var image_url: String?
var is_closed: Bool?
var url: String?
var review_count: Int?
var categories: [Category]?
...
With Lesson 6 being to turn that data into user-friendly views. For this we’ve been introduced to Section, which allows us to use a header/footer that “sticks” to the view when scrolling would previously force it off the screen. We’re also using multiple sub-views to keep the code tidy and more easily manageable.
struct BusinessList: View {
@EnvironmentObject var model: ContentModel
var body: some View {
ScrollView {
LazyVStack (alignment: .leading, pinnedViews:[.sectionHeaders]) {
BusinessSection(title: "Restaurants", businesses: model.restaurants)
BusinessSection(title: "Sights", businesses: model.sights)
}
}
}
}
struct BusinessSection: View {
var title: String
var businesses: [Business]
var body: some View {
Section(header: BusinessSectionHeader(title: title)) {
ForEach(businesses) { business in
Text(business.name ?? "")
Divider()
}
}
}
}
struct BusinessSectionHeader: View {
var title: String
var body: some View {
ZStack (alignment: .leading) {
Rectangle()
.foregroundColor(.white)
Text(title)
.font(.headline)
}
}
}
This reminds me very much of my PHP days. After the initial rush-job to set up my script in a hurry, leading to everything being pretty chaotic run by an overwhelming large main script, I started moving chunks out into more easily manageable files.