gpt4 book ai didi

ios - SwiftUI @FocusState - 如何赋予它初始值

转载 作者:行者123 更新时间:2023-12-04 12:55:34 24 4
gpt4 key购买 nike

我很高兴看到 TextField 增强:focused(...): https://developer.apple.com/documentation/swiftui/view/focused(_:)
我想用它来展示一个非常简单的 SwitfUI View ,它只包含一个 TextField,它的焦点是立即打开键盘。无法使其工作:

    struct EditTextView: View {
@FocusState private var isFocused: Bool
@State private var name = "test"
// ...
var body: some View {
NavigationView {
VStack {
HStack {
TextField("Enter your name", text: $name).focused($isFocused)
.onAppear {
isFocused = true
}
// ...
哪里不对了?我很难给它默认值。

最佳答案

我也无法在 Xcode 13,beta 5 上完成这项工作。为了解决这个问题,我推迟了对 isFocused = true 的调用。 . 那行得通!
我在这个错误背后的理论是在 onAppear 的时候TextField 还没有准备好成为第一响应者,所以 isFocused = true和 iOS 调用 becomeFirstResponder在幕后,但它失败了(例如, View 层次结构尚未完成设置)。

struct MyView: View {

@State var text: String
@FocusState private var isFocused: Bool

var body: some View {
Form {
TextEditor(text: $text)
.focused($isFocused)
.onChange(of: isFocused) { isFocused in
// this will get called after the delay
}
.onAppear {
// key part: delay setting isFocused until after some-internal-iOS setup
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
isFocused = true
}
}
}
}
}

关于ios - SwiftUI @FocusState - 如何赋予它初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68073919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com