【问题标题】:Passing down @FocusState to another view将@FocusState 传递给另一个视图
【发布时间】:2022-06-10 21:03:03
【问题描述】:

我想知道如何将@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)
        }
        
    }
  }
}

我如何能够将其传递给 View2。还是有更好的方法来重用自定义文本字段?将不胜感激。

【问题讨论】:

    标签: swiftui


    【解决方案1】:

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

    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)
            }
    
        }
      }
    }
    

    backup

    【讨论】:

    • 我想知道如何在 view2 上单击按钮时将focusedField 设置为nil。它说它在 View2 中是不可变的,只是在想我怎么能做到。
    • 要在View2中设置focusedField,不改focused.wrappedValue吗?
    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2021-06-12
    • 2012-06-12
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多