首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将@FocusState传递给另一个视图

将@FocusState传递给另一个视图
EN

Stack Overflow用户
提问于 2021-11-28 06:40:10
回答 1查看 1.2K关注 0票数 7

我想知道你怎么能把@FocusState传给另一个视图。下面是一些示例代码。

代码语言:javascript
运行
复制
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。还是有更好的方法重用自定义textfield?会很感激你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-28 07:04:06

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

代码语言:javascript
运行
复制
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)
        }

    }
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70141230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档