如何创建一个带有“完成”按钮的水平 TextField 以在 SwiftUI 中将其关闭?

问题描述 投票:0回答:1

我的应用程序中有文本字段,需要有水平轴(多行),以便用户可以输入长文本并轻松查看他们在做什么。我想要一个完成按钮,让他们关闭屏幕键盘,或者更好的是,跳到下一个字段(如果有)。我真的很喜欢一个纯粹的 SwiftUI 解决方案

我已经尝试过了

  • 使用
    .submitLabel(.done)
    ,这会创建完成按钮,但按下时会添加新行,而不是关闭键盘。
  • 使用
    onCommit
    TextField
    参数并传入一个关闭键盘的函数。这可行,但您不能在给定的
    onCommit
     上同时使用 
    axis
    TextField
  • 参数
  • 设置
    .lineLimit(nil)
    ,没有效果
  • 将 textView 包装在
    HStack
    中,这当然没有效果
swiftui textfield
1个回答
0
投票

您可以使用

@FocusState
包装器结合
.focused(_)
修饰符来控制文本字段的焦点(无论它是否处于活动状态),如下所示:

import SwiftUI

struct ContentView: View {
    
    // @FocusState can change the focus of a textfield (if it is active or not)
    @FocusState var isEmail: Bool  
    @FocusState var isUsername: Bool  
    @FocusState var isPassword: Bool  
    
    @State var email: String = ""
    @State var username: String = ""
    @State var password: String = ""
    
    var body: some View {
        VStack {
            TextField("Email", text: $email, axis: .horizontal)
                .submitLabel(.continue)
                .focused($isEmail) // connects the `isEmail` focus state value to the email textfield 
                .onSubmit() {
                    // on submit, when the user hits enter, the email focus gets removed and the username focus gets activated
                    isEmail = false
                    isUsername = true
                }
            
            TextField("Username", text: $username, axis: .horizontal)
                .submitLabel(.continue)
                .focused($isUsername)
                .onSubmit() {
                    isUsername = false
                    isPassword = true
                }
            
            SecureField("Password", text: $password)
                .submitLabel(.done)
                .focused($isPassword)
                .onSubmit() {
                    isPassword = false 
                }
        }
        .textFieldStyle(.roundedBorder)
        .padding()
        .onAppear {
            isEmail = true // default focus when the view appears is the mail textfield
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.