要在SwiftUI中实现按下回车键而不关闭软键盘,您可以使用onReceive
修饰符来捕获回车键的按下事件,并通过UIApplication.shared.sendAction
方法发送一个自定义的动作来阻止键盘关闭。
以下是一个示例代码:
import SwiftUI
struct ContentView: View {
@State private var text: String = ""
var body: some View {
VStack {
TextField("Enter text", text: $text)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
在这个示例中,我们使用onReceive
修饰符来监听键盘将要关闭的通知。当键盘将要关闭时,我们通过UIApplication.shared.sendAction
方法发送一个resignFirstResponder
动作,这会阻止键盘关闭。
请注意,为了使onReceive
修饰符能够监听键盘通知,您需要将其放置在包含TextField
的父视图中。在这个示例中,我们将其放置在一个VStack
中。
希望这可以帮助到您!