#ios #swift #xcode #swiftui #keyboard
Вопрос:
Я создаю панель инструментов для клавиатуры, но я не знаю, почему моя панель инструментов расположена в верхней части текущего представления. Мне нужно поместить панель инструментов в верхней части клавиатуры, вот как это выглядит прямо сейчас
Это и есть код
import Foundation
import SwiftUI
struct KeyboardObserving: ViewModifier {
@State var keyboardHeight: CGFloat = 0
@State var keyboardAnimationDuration: Double = 0
@State var currentHeight: CGFloat = 0
func body(content: Content) -> some View {
content
.padding([.bottom], keyboardHeight)
.edgesIgnoringSafeArea((keyboardHeight > 0) ? [.bottom] : [])
.animation(.easeOut(duration: keyboardAnimationDuration))
.onReceive(
NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
.receive(on: RunLoop.main),
perform: updateKeyboardHeight
)
}
func updateKeyboardHeight(_ notification: Notification) {
guard let info = notification.userInfo else { return }
// Get the duration of the keyboard animation
keyboardAnimationDuration = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
currentHeight = keyboardSize.height
print("currentheiht (currentHeight)") // output 336.0
}
guard let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
// If the top of the frame is at the bottom of the screen, set the height to 0.
if keyboardFrame.origin.y == UIScreen.main.bounds.height {
keyboardHeight = 0
} else {
// IMPORTANT: This height will _include_ the SafeAreaInset height.
keyboardHeight = keyboardFrame.height
print("keyboad (keyboardHeight)")// output 336.0
}
}
}
extension View {
func keyboardObserving() -> some View {
self.modifier(KeyboardObserving())
}
}
Комментарии:
1. проверьте текстовое поле
inputAccessoryView
.2. Текстовое поле в SwiftUI не имеет определенного метода. @RTXGamer
3. затем оберните текстовое поле с видом вспомогательного устройства ввода с помощью UIViewRepresentable