gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:05 29 4
gpt4 key购买 nike

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

此移动在转换源 (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
}
}

最佳答案

使用 View 修改器

可以使用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 { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue }
.map { $0.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 = $0 }
}
}

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() 会自动在你的 View 中添加一个填充,它更优雅。

关于ios - 如何使用SwiftUI在多个屏幕上获取键盘高度并移动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746006/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com