Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Created June 20, 2020 19:59
Show Gist options
  • Save PetreVane/bd4f2878e813d00b1d6c34163e7503ee to your computer and use it in GitHub Desktop.
Save PetreVane/bd4f2878e813d00b1d6c34163e7503ee to your computer and use it in GitHub Desktop.
Two examples of iterating over a list of elements, with ForEach. See bellow how to add a PickerView
import SwiftUI
struct ContentView: View {
let tips = ["Dream of mice", "Make some Origami", "Get the dog juggling", "Eating candies", "Sniffing weird stuff"]
var body: some View {
// Simple iteration where there list contains only a bunch of Strings
ForEach(tips, id: \.self) { tip in
VStack {
Image("Meditate")
.resizable()
.scaledToFit()
Text("Cat relaxation tip: \(tip)")
}
}
// More complex iteration over a list of instances
VStack {
ForEach(RelaxationTip.demoTips) { tipModel in
VStack {
Image(tipModel.imageName)
.resizable()
.scaledToFit()
Text(tipModel.tip)
}
}
}
}
}
// Here is the list of instances. Remember: It is mandatory that the Model conforms to Identifiable protocol, so each instance can be identified by an unique identifier
import SwiftUI
struct RelaxationTip: Identifiable {
var id = UUID()
var imageName: String
var tip: String
}
extension RelaxationTip {
static let demoTips: [RelaxationTip] = [
RelaxationTip(imageName: "Meditate", tip: "Meditate with your human pet"),
RelaxationTip(imageName: "Juggle", tip: "Juggle for a while"),
RelaxationTip(imageName: "DreamOfMice", tip: "Dream of mice"),
RelaxationTip(imageName: "Origami", tip: "Make some Origami"),
RelaxationTip(imageName: "MakeDogJuggle", tip: "Get the dog juggling"),
]
}
// Adding a Picker
struct PickerViewExample: View {
// reference to array of instances
let tips = RelaxationTip.demoTips
// holds the selected value index
@State private var selectedPickerIndex = 0
var body: some View {
VStack {
Picker(selection: $selectedPickerIndex, label: Text("Pick your mood")) {
ForEach(0 ..< tips.count) { index in
HStack {
Image(self.tips[index].imageName)
.resizable()
.scaledToFit()
Text(self.tips[index].tip)
}
}
}
Text("You've selected \(self.tips[self.selectedPickerIndex].tip)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment