首页 > 解决方案 > 自定义键盘工具栏

问题描述

我为键盘创建了一个工具栏,但我不知道为什么我的工具栏位于当前视图的顶部。我需要将工具栏放在键盘顶部 这是现在的样子

这是代码

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())
      }
    }

标签: iosswiftxcodeswiftuikeyboard

解决方案


推荐阅读