将 @FocusState 传递到另一个视图

Lui*_*rez 24 swiftui

我想知道如何将 @FocusState 传递给另一个视图。这是一些示例代码。

struct View1: View {
  enum Field {
    case username, password
  }

  @State var passwordText: String = ""
  @FocusState var focusedField: Field?

  var body: some View {
    // How would I be able to pass the focusedField here?
    View2(text: $passwordText, placeholder: "Password")

    //TextField("Password", text: $passwordText)
        //.frame(minHeight: 44)
        //.padding(.leading, 8)
        //.focused($focusedField, equals: .password)

    // How would I be able to add the commented code above to View2
  }
}

struct View2: View {
  @Binding var text: String
  let placeholder: String

  var body: some View {
    HStack {
        TextField(placeholder, text: $text)
            .frame(minHeight: 44)
            .padding(.leading, 8)
            // How would I be able to add this
            //.focused(binding: , equals: )
        if text.count > 0 {
            Image(systemName: "xmark.circle.fill")
                .font(.headline)
                .foregroundColor(.secondary)
                .padding(.trailing, 8)
        }
        
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能将它传递给 View2. 或者有更好的方法来重用自定义文本字段吗?将不胜感激任何帮助。

Asp*_*eri 24

您可以将其绑定作为参数传递,例如

struct View1: View {
  enum Field {
    case username, password
  }

  @State var passwordText: String = ""
  @FocusState var focusedField: Field?

  var body: some View {
    View2(text: $passwordText, placeholder: "Password", focused: $focusedField)
  }
}

struct View2: View {
  @Binding var text: String
  let placeholder: String
  var focused: FocusState<View1.Field?>.Binding     // << here !!

  var body: some View {
    HStack {
        TextField(placeholder, text: $text)
            .frame(minHeight: 44)
            .padding(.leading, 8)
            .focused(focused, equals: .password)     // << here !!
        if text.count > 0 {
            Image(systemName: "xmark.circle.fill")
                .font(.headline)
                .foregroundColor(.secondary)
                .padding(.trailing, 8)
        }

    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是可行的,但是我如何使预览能够处理如此奇怪的变量呢?var focus: FocusState&lt;View1.Field?&gt;.Binding ? (3认同)

Xax*_*xus 13

存储FocusState<Value>.Binding似乎对我不起作用

我让它像这样工作,它的行为似乎就像常规绑定的工作方式一样:

struct ParentView: View {
    @State var text: String = ""
    @FocusState var isFocused: Bool
    
    var body: some View {
        ChildView(text: $text, isFocused: $isFocused)
    }
}

struct ChildView: View {
    @Binding var text: String
    @FocusState.Binding var isFocused: Bool

    var body: some View {
        TextField($text)
            .focused($isFocused)
    }
}
Run Code Online (Sandbox Code Playgroud)