SwiftUI Cheatsheet
A friendly way to remember some SwiftUI snippets.
SwiftUI Children Limits
SwiftUI by default limits its children to 10. However, this doesn’t mean that we can’t have more than ten elements in the same view. We just need to add the Group {...}
directive.
In the following example, it can be noticed that we have seven children under the Form {...}
directive and one of them is a Group {...}
which contains five children itself. That’s the trick.
Form with 10+ elements
Form {
Text("Field #1")
Text("Field #2")
Text("Field #3")
Text("Field #4")
Text("Field #5")
Text("Field #6")
Group {
Text("Field #7")
Text("Field #8")
Text("Field #9")
Text("Field #10")
Text("Field #11")
}
}
Group vs. Section
struct ContentView: View {
var body: some View {
Form {
Group {
Text("This field is ...")
}
Group {
Text("exactly next to this one!")
}
Section {
Text("This field is separated.")
}
}
}
}
NavigationView
struct ContentView: View {
var body: some View {
NavigationView {
Form {
Group {
Text("Field #1")
}
}
.navigationTitle("Navigation")
.navigationBarTitleDisplayMode(.inline)
}
}
}
TapCount
struct ContentView: View {
@State private var tapCount = 0
var body: some View {
Button("Tap Count: \(tapCount)") {
tapCount += 1
}
}
}
TextField
struct ContentView: View {
@State private var textField = ""
var body: some View {
NavigationView {
Form {
TextField("Enter text ...", text: $textField)
Text(textField)
}
.navigationTitle("Navigation")
}
}
}
Picker
struct ContentView: View {
let drinks = ["Beer", "Wine", "Champagne"]
@State private var selectedDrink = "Beer"
var body: some View {
NavigationView {
Form {
Picker("Select your drink ...", selection: $selectedDrink) {
ForEach(drinks, id: \.self) { drink in
Text(drink)
}
}
}
.navigationTitle("Navigation")
}
}
}
ForEach
struct ContentView: View {
let drinks = ["Beer", "Wine", "Champagne"]
var body: some View {
NavigationView {
Form {
ForEach(drinks, id: \.self) {
Text($0)
}
}
.navigationTitle("Navigation")
}
}
}
TextField with Currency Format
struct ContentView: View {
@State private var checkAmount = 0.0
static let currencyCode = Locale.current.currencyCode ?? "USD"
static let checkAmountFormat: FloatingPointFormatStyle<Double>.Currency = .currency(code: currencyCode)
var body: some View {
NavigationView {
Form {
Section {
TextField("Check Amount",
value: $checkAmount,
format: ContentView.checkAmountFormat)
.keyboardType(.decimalPad)
}
Section {
Text(checkAmount, format: ContentView.checkAmountFormat)
}
}
.navigationTitle("Navigation")
}
}
}