I recently started reading the documentation with the goal of creating SwiftUI 'recipies' in playgrounds
Excellent way to learn, experiment, and document your understanding.
In initliser 5, what is the purpose of having the label be a trailing closure? Can you show me an example?
Let's Experiment!
What is the purpose of a Label? See -> Apple Docs: Label
In older versions of SwiftUI, if you wanted text
and an icon
side-by-side, you'd hack together an HStack
. This was such a common pattern that the Label
was introduced in iOS 14.
Demonstrate a Label
struct LabelView: View {
// Collect string characters here.
@State private var sekretCode = ""
// Determine if we show or hide the code
@State private var showCode = false
// Calculate an appropriate icon
var labelIconName: String { sekretCode.isEmpty ? "lock" : "lock.fill" }
// This is a function that takes nothing and returns a Label
private func makeLabel() -> Label<Text, Image> {
Label("Kode", systemImage: labelIconName)
}
var body: some View {
VStack{
Text("Watch the label's icon...").font(.callout)
// Use the computed Label in the Toggle()
Toggle(isOn: $showCode, label: makeLabel )
Text(sekretCode).animation(.smooth)
}
.font(.largeTitle)
.onChange(of: showCode) { _, newValue in
// Notice the Label's icon changes....
if newValue { sekretCode = "sekret" } else { sekretCode = "" }
}
.padding(.horizontal)
Spacer()
}
}
Note that the function makeLabel()
takes nothing and returns a Label
.
TextField Initialiser
Apple's documentation for TextField
provides this initialiser:
init(text: Binding<String>, prompt: Text?, label: () -> Label)
Creates a text field with a prompt generated from a Text.
Available when Label conforms to View.
So experiment with this. Initialise a TextField
providing nil
for the prompt, but provide a function that takes nothing and returns a Label.
Keep Coding