我在 MacOS 的警报中添加了一个文本字段。但是,当警报显示时,TextField 不会获得焦点。这是我测试过的代码。这可能吗?如果这是一个错误,请建议其他解决方法。
import SwiftUI
struct ContentView: View {
@State private var presented = false
@State private var username = ""
@FocusState private var focused: Bool
var body: some View {
VStack {
Button(action: {
focused = true
presented = true
}, label: {
Text("Click to show Alert")
})
}
.alert("", isPresented: $presented, actions: {
VStack {
TextField("User name (email address)", text: $username)
.focusable()
.focused($focused)
Button(action: {}, label: { Text("OK") })
}
.onAppear() {
// Try setting focus with a delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
focused = true
})
}
}, message: {
Text("The textField in this alert doesn't get the focus. Therefore, a manual click is needed to set focus and start typing.")
})
}
}
最佳答案
我可以确认焦点在 Alert
中不起作用。可能的解决方法是使用自定义 Sheet
:
struct ContentView: View {
@State private var presented = false
@State private var username = ""
@FocusState private var focused: Bool
var body: some View {
VStack {
Button(action: {
presented = true
focused = true
}, label: {
Text("Click to show Sheet")
})
}
.sheet(isPresented: $presented, content: {
VStack {
// App Icon placeholder
RoundedRectangle(cornerRadius: 8)
.fill(.secondary)
.frame(width: 48, height: 48)
.padding(12)
Text("The textField in this alert doesn't get the focus. Therefore, a manual click is needed to set focus and start typing.")
.font(.caption)
.multilineTextAlignment(.center)
TextField("User name (email address)", text: $username)
.focused($focused)
.padding(.vertical)
Button(action: {
presented = false
}, label: {
Text("OK")
.frame(maxWidth: .infinity)
})
.buttonStyle(.borderedProminent)
}
.padding()
.frame(width: 260)
})
}
}
关于macos - SwiftUI - MacOS - 警报中的文本字段未获得焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74831978/