Skip to main content

Textfeld mit automatischem Fokus

Beschreibung

Diese View zeigt ein Textfeld, das beim Erscheinen der View automatisch den Fokus erhält. Dadurch öffnet sich die Tastatur direkt und der Nutzer kann ohne zusätzlichen Tap tippen. Die Fokussierung wird leicht verzögert ausgelöst, um den Initialaufbau der View zu berücksichtigen.

🔍 Zweck

  • Schnellstart für Eingaben ohne zusätzlichen Tap
  • Suchfeld mit Auto-Fokus auf einer Übersichtsseite
  • Login oder Einmalcode Eingabe mit sofortigem Fokus
  • Prototyping von Formularinteraktionen
  • Accessibility Verbesserung durch klare Fokusführung

🖥️ Betriebssystem

iOS

📄 Codebeispiel

import SwiftUI

@main
struct AutofocusTextFieldApp: App {
    var body: some Scene {
        WindowGroup {
            AutofocusTextFieldExample()
        }
    }
}

public struct AutofocusTextFieldExample: View {
    // Store the current input text
    @State private var input = ""
    // Manage focus for the text field
    @FocusState private var isFocused: Bool

    public init() {}

    public var body: some View {
        VStack(spacing: 12) {
            // Title to explain the sample
            Text("Auto Focus Text Field")
                .font(.headline)

            // The text field that should receive focus on appear
            TextField("Start typing...", text: $input)
                .focused($isFocused) // Bind focus state
                .textFieldStyle(.roundedBorder)
                .submitLabel(.done)
        }
        .padding()
        .onAppear {
            // Defer focus until after the view has appeared
            // This avoids race conditions during initial layout
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                isFocused = true
            }
        }
    }
}

// Modern Swift 5.10+ preview syntax
#Preview {
    AutofocusTextFieldExample()
}