UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Wakanda 'TextField' has a 'label' closure? Why tho?

Forums > SwiftUI

Dear all,

  • I recently started reading the documentation with the goal of creating SwiftUI 'recipies' in playgrounds as often advised by @Obelix. I decided to start with TextField.
  • Focusing on string inputs only, I discovered that there were 5 different ways to initialise them — I decided to practice them all. (It was interesting how the first 4 TextField initialisers differentiated between LocalisedStringKey and StringProtocol, along with the optional 'promt' parameter — not sure I understand it all 100% though... not yet.)
  • Everything was going well enough until the last TextField initialiser, one that uses a 'label' view, which I'm unable to understand without an example. I don't know how to make use of this, and I would like a see some examples, if you have any.

Here's what specifically confuses me:

  1. In initialisers 2 and 4, what is the purpose of the 'prompt' when you can have a label? Why does 'prompt' replace the 'label' as a placeholder when you have both? Is it that labels are read out by voiceovers, but prompts are not? Surely that can't be it.
  2. In initliser 5, what is the purpose of having the label be a trailing closure? Can you show me an example? (If I had to guess I'd say that I can make the label look like anything, for example — instead of a flat box, the label looks like a capsule that the user is supposed to type into. Is that it?)

I hope someone understands what to you must be a relatively basic question. Here's my practice code for this topic. Hope you can help.

Best, Ara.

//
//  ContentView.swift
//  MyPrePlayground
//
//  Created by Ara on 31/03/24.
//

import SwiftUI
struct ContentView: View {
    @State private var userInput = ""
    let doNotTranslateThisTitle = "Always English"

    var body: some View {

        Form {

//        https://developer.apple.com/documentation/swiftui/textfield/init(_:text:)-4lffk
            Section("Localised.String.Key") {
                Section("init Type 1") {
                    TextField("Simple", text: $userInput)
                }

//        https://developer.apple.com/documentation/swiftui/textfield/init(_:text:prompt:)-70zi2
                Section("init Type 3 (prompt)") {
                    TextField("Description", text: $userInput, prompt: Text("Why prompt, when label?"))
                }
            }

//        https://developer.apple.com/documentation/swiftui/textfield/init(_:text:)-2laoi
            Section("String Protocol") {
                Section("init Type 2") {
                    TextField(doNotTranslateThisTitle, text: $userInput)
                }

//        https://developer.apple.com/documentation/swiftui/textfield/init(_:text:prompt:)-4kzyv
                Section("init Type 4 (prompt)") {
                    TextField(doNotTranslateThisTitle, text: $userInput, prompt: Text("Why prompt, when label?"))
                }
            }

//        https://developer.apple.com/documentation/swiftui/textfield/init(text:prompt:label:)
            Section("Eh?") {
                Section("init Type 5") {
                    TextField(text: $userInput, prompt: Text("So how come prompts > label?")) {
                        Text("How do I take advantage of this closure label? I see that I can pass in a 'title string' that conforms to 'String Protocol', and also pass in 'LocalisedStringKey'. So what's the catch? What's special about this label?")
                    }
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

   

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

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.