1

我正在尝试为我TextField在 SwiftUI 中的一些添加键盘工具栏。

我有一个这样定义的视图:

struct Test: View {
    
    @State private var name: String = ""
    @State private var address: String = ""
    @State private var username: String = ""
    @State private var password: String = ""
    
    enum Field: Hashable {
        case nameField
        case addressField
        case usernameField
        case passwordField
    }
    @FocusState private var focusedField: Field?
    
    var body: some View {
        Form {
            Section {
                TextField("Name", text: $name)
                    .focused($focusedField, equals: .nameField)
                    .submitLabel(.next)
                
                TextField("Address", text: $address)
                    .focused($focusedField, equals: .addressField)
                    .submitLabel(.next)
                
                TextField("Username", text: $username)
                    .focused($focusedField, equals: .usernameField)
                    .submitLabel(.next)
                
                SecureField("Password", text: $password)
                    .focused($focusedField, equals: .passwordField)
                    .submitLabel(.done)
            }
        }
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                if focusedField == .addressField {
                    Button("Test", action: {})
                }
                Button("Done", action: {
                    print(focusedField)
                })
            }
        }
    }
}

The problem is, the additional toolbar button appears when the wrong field is selected.

在此处输入图像描述

我也尝试过使用@FocusedValue这样的:

...
@FocusedValue(\.field) var field: Field?
...
   TextField("Name", text: $name)
      .focused($focusedField, equals: .nameField)
      .submitLabel(.next)
      .focusedValue(\.field, .nameField)
...
      .focusedValue(\.field, .addressField)
...
      .focusedValue(\.field, .usernameField)
...
      .focusedValue(\.field, .passwordField)
...
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                if field == .addressField {
                    Button("Test", action: {})
                }
                Button("Done", action: {
                    print(field)
                })
            }
        }

但这给出了相同的结果。就好像在focused设置状态之前决定了工具栏。我不确定这是否是一个可能的错误,或者我做错了?

尽管即使我完成了上述工作,它也不能解决我只想要一个文本字段的工具栏的整体问题,但是当我尝试像这样设置它时,我根本没有工具栏。

.toolbar {
    ToolbarItemGroup(placement: .keyboard) {
        if field == .addressField {
            Button("Test", action: {})
        } else {
            EmptyView()
        }
    }
}
4

0 回答 0