将@FocusState传递到另一个视图



我想知道如何将@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呢。或者有更好的方法来重用自定义文本字段吗?如果有任何帮助,我将不胜感激。

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

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

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

相关内容

  • 没有找到相关文章