以下是我的SwiftUI码:

struct ContentView : View {

    @State var showingTextField = false
    @State var text = ""

    var body: some View {
        return VStack {
            if showingTextField {
                TextField($text)
            }
            Button(action: { self.showingTextField.toggle() }) {
                Text ("Show")
            }
        }
    }
}

我想要的是当文本字段变为visible时,使文本字段成为第一响应者(即接收焦点并弹出键盘).

推荐答案

iOS 15.0+

macOS 12.0+,

Mac Catalyst 15.0+,

tvOS 15.0+,

watchOS 8.0+

Use 专注的(:) if you have a single TextField.

专注的(:)

通过将其焦点状态绑定到给定的Boolean状态值来修改此视图.

struct NameForm: View {
    
    @FocusState private var isFocused: Bool
    
    @State private var name = ""
    
    var body: some View {
        TextField("Name", text: $name)
            .focused($isFocused)
        
        Button("Submit") {
            if name.isEmpty {
                isFocued = true
            }
        }
    }
}

Use 专注(等于) should you have multiple TextFields.

专注(等于)

通过将焦点状态绑定到给定的状态值来修改此视图.

struct LoginForm: View {
    enum Field: Hashable {
        case usernameField
        case passwordField
    }

    @State private var username = ""
    @State private var password = ""
    @FocusState private var focusedField: Field?

    var body: some View {
        Form {
            TextField("Username", text: $username)
                .focused($focusedField, equals: .usernameField)

            SecureField("Password", text: $password)
                .focused($focusedField, equals: .passwordField)

            Button("Sign In") {
                if username.isEmpty {
                    focusedField = .usernameField
                } else if password.isEmpty {
                    focusedField = .passwordField
                } else {
                    handleLogin(username, password)
                }
            }
        }
    }
}

SwiftUI文档


使现代化

我测试了xCode version 13.0 beta 5 (13A5212g)次.它起作用了

Swift相关问答推荐

NSWindow中以编程方式创建的TextField快捷方式与SwiftUI

如何将CodingKeys作为数组而不是枚举传递到类外部的函数中?

如何使泡泡上的箭头直达封闭矩形

在NavigationStack上设置拐角半径:SwiftUI中的无响应内容视图区

Swift通过设置变量B自动设置变量A的值

如何为等待函数调用添加超时

从 Swift Vapor Server 中调用 ShazamKit

在主要参与者中启动分离任务和调用非隔离函数之间的区别

响应 UITextField (UIViewRepresentable) 中的特定按键

符合协议 - 错误?

为什么 Swift Tuples 只能在元素个数小于等于 6 的情况下进行比较?

在视图中设置所有变量

VStack SwiftUI 中的动态内容高度

如何防止 UITableViewCell 移动(Swift 5)

如何在 Xcode 中的 UITests 下以通用方式访问后退栏按钮项?

SwiftUI 中的 .primary 和 .secondary colored颜色 是什么?

为 UIActivityViewController Swift 设置不同的活动项

iOS:检测设备是否为 iPhone X 系列(无框)

如何在Swift中找出字母是字母数字还是数字

Xcode 和 Swift - 没有标题栏但有关闭、最小化和调整大小按钮的窗口