您可以使用
获取键盘的高度.onReceive(NotificationCenter
.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
.map { $0.cgRectValue.height }, perform: { height in
self.height = height //Adjust the height based on the keyboard
})
然后通过设置将键盘带入/带出
@FocusState var isFocused: Bool
到
true
/false
这是完整的示例。
import SwiftUI
struct KeyboardHeightView: View {
//Use this to bring/dismiss keyboard
@FocusState var isFocused: Bool
@State private var height: CGFloat = 300
@State private var text: String = "test"
@ScaledMetric var buttonHeight = 40
var body: some View {
VStack{
TextEditor(text: $text)
.focused($isFocused)
//Parent for buttons and actions
Rectangle()
.fill(Color.white)
.border(Color.green)
.overlay {
//Area for buttons and actions
VStack {
//Space for the buttons
HStack{
Text("tap to dismiss")
.onTapGesture {
isFocused = false //Dismiss Keyboard
}
}
.frame(height: buttonHeight)
.frame(maxWidth: .infinity)
.border(Color.red)
//Space for other actions.
Spacer()
}
}
.frame(height: height + buttonHeight) //Keyboard + the space for the buttons that dismiss keyboard and show actions
}.ignoresSafeArea(.keyboard)
.edgesIgnoringSafeArea(.bottom)
.onReceive(NotificationCenter
.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
.map { $0.cgRectValue.height }, perform: { height in
self.height = height //Adjust the height based on the keyboard
})
.task {
isFocused = true //Show keyboard when the View appears
}
}
}
#Preview {
KeyboardHeightView()
}