Skip to content
This repository was archived by the owner on Jun 24, 2024. It is now read-only.

Latest commit

 

History

History
78 lines (62 loc) · 2.37 KB

10023.md

File metadata and controls

78 lines (62 loc) · 2.37 KB
contributors
zntfdr
  • Focus is the system that lets your app take input from keyboards, remotes, game controllers, accessible switch controls, and other sources that -- unlike touch inputs -- are not tied to specific screen coordinates
  • the focus view is often drawn with special embellishments, making it easy for people to predict where their input will be directed

Focus state API

struct LoginForm {
  enum Field: Hashable {
    case username
    case password
  }

  @State private var username = ""
  @State private var password = ""
  @FocusState private var focusedField: Field?

  var body: some View {
    Form {
      TextField("Username", text: $username)
        .focused($focusedField, equals: .username)

      SecureField("Password", text: $password)
        .focused($focusedField, equals: .password)

      Button("Sign In", action: onSignInTap)
    }
  }

  /// Puts the focus on one of the text fields if their data is missing.
  func onSignInTap() {
    if username.isEmpty {
      focusedField = .username
    } else if password.isEmpty {
      focusedField = .password
    } else {
      handleLogin(username, password)
    }
  }
}
  • Note that the FocusState value is optional (Field? in the example): nil is used for cases where focus is in an unrelated part of the screen.

Focus sections

  • FocusStates are not just for text fields, but can also be used to navigate the focus of the app (think browsing tvOS)
  • new focusSection() view modifier, which tells SwiftUi that this view is capable of accepting focus if it contains any focusable subviews
  • this is used (in tvOS) to navigate between different/separate focus sections of the screen
struct ContentView: View {

  var body: some View {
    HStack {
      VStack) {
         ...
      }
      .focusSection()

      VStack {
        ...
      }
      .focusSection()
    }
  }
}