如何使用SwiftUI在多个屏幕上获取键盘高度并移动按钮

How to get the keyboard height on multiple screens with SwiftUI and move the button

以下代码获取键盘显示时的键盘高度,并按键盘高度移动按钮。

此移动在转换源 (ContentView) 和转换目标 (SecibdContentView) 中以相同的方式执行,但按钮不会在转换目标处移动。

如何让按钮在多个屏幕上移动相同?

import SwiftUI

struct ContentView: View {
    @ObservedObject private var keyboard = KeyboardResponder()

    var body: some View {
        NavigationView {
            VStack {
                Text("ContentView")

                Spacer()

                NavigationLink(destination: SecondContentView()) {
                    Text("Next")
                }
                .offset(x: 0, y: -keyboard.currentHeight)
            }
        }
    }
}

import SwiftUI

struct SecondContentView: View {
    @ObservedObject private var keyboard = KeyboardResponder()

    var body: some View {
        VStack {
            Text("SubContentView")

            Spacer()

            NavigationLink(destination: ThirdContentView()) {
                Text("Next")
            }
            .offset(x: 0, y: -keyboard.currentHeight)
        }
    }
}

class KeyboardResponder: ObservableObject {
    private var _center: NotificationCenter
    @Published var currentHeight: CGFloat = 0

    init(center: NotificationCenter = .default) {
        _center = center
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    deinit {
        _center.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            currentHeight = keyboardSize.height
        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        currentHeight = 0
    }
}

您的代码缺少一些东西。没有 NavigationView,也没有用于显示键盘的 TextFields。考虑更新您的代码。

无论如何,将keyboardFrameBeginUserInfoKey替换为keyboardFrameEndUserInfoKey即可轻松解决问题。

更新:

您还需要使用同一个KeyboardResponder,否则您将创建多个实例。或者,您可以将其放入您的环境中。

并且您忘记将 TextFields 添加到您的代码中,因此键盘将出现以对其进行测试。

以下代码有效:

import SwiftUI

struct ContentView: View {
    @ObservedObject private var keyboard = KeyboardResponder()

    var body: some View {
        NavigationView {
            VStack {
                Text("ContentView")
                TextField("enter text", text: .constant(""))
                Spacer()

                NavigationLink(destination: SecondContentView(keyboard: keyboard)) {
                    Text("Next")
                }
                .offset(x: 0, y: -keyboard.currentHeight)
            }
        }
    }
}

import SwiftUI

struct SecondContentView: View {
    @ObservedObject var keyboard: KeyboardResponder

    var body: some View {
        VStack {
            Text("SubContentView")
            TextField("enter text", text: .constant(""))
            Spacer()

            NavigationLink(destination: Text("ThirdContentView()")) {
                Text("Next")
            }
            .offset(x: 0, y: -keyboard.currentHeight)
        }
    }
}

class KeyboardResponder: ObservableObject {
    private var _center: NotificationCenter
    @Published var currentHeight: CGFloat = 0

    init(center: NotificationCenter = .default) {
        _center = center
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    deinit {
        _center.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            currentHeight = keyboardSize.height
        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        currentHeight = 0
    }
}

SwiftUI + 合并

@Published var keyboardHeight: CGFloat = 0 // if one is in ViewModel: ObservableObject

private var cancellableSet: Set<AnyCancellable> = []
    
init() {
        
     NotificationCenter.default.publisher(for: UIWindow.keyboardWillShowNotification)
       .map {
             guard
                 let info = [=10=].userInfo,
                 let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
                 else { return 0 }

             return keyboardFrame.height
         }
         .assign(to: \.keyboardHeight, on: self)
         .store(in: &cancellableSet)
        
     NotificationCenter.default.publisher(for: UIWindow.keyboardDidHideNotification)
         .map { _ in 0 }
         .assign(to: \.keyboardHeight, on: self)
         .store(in: &cancellableSet)
    }
    

使用 ViewModifier

可以使用swiftui的ViewModifier,简单多了

import SwiftUI
import Combine

struct KeyboardAwareModifier: ViewModifier {
    @State private var keyboardHeight: CGFloat = 0

    private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
        Publishers.Merge(
            NotificationCenter.default
                .publisher(for: UIResponder.keyboardWillShowNotification)
                .compactMap { [=10=].userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
                .map { [=10=].cgRectValue.height },
            NotificationCenter.default
                .publisher(for: UIResponder.keyboardWillHideNotification)
                .map { _ in CGFloat(0) }
       ).eraseToAnyPublisher()
    }

    func body(content: Content) -> some View {
        content
            .padding(.bottom, keyboardHeight)
            .onReceive(keyboardHeightPublisher) { self.keyboardHeight = [=10=] }
    }
}

extension View {
    func KeyboardAwarePadding() -> some View {
        ModifiedContent(content: self, modifier: KeyboardAwareModifier())
    }
}

在你看来

struct SomeView: View {
    @State private var someText: String = ""

    var body: some View {
        VStack {
            Spacer()
            TextField("some text", text: $someText)
        }.KeyboardAwarePadding()
    }
}

KeyboardAwarePadding()会自动在你的视图中添加一个padding,更优雅。