如何在 SwiftUI 中显示键盘时显示完整列表 [英] How to show complete List when keyboard is showing up in SwiftUI

查看:13
本文介绍了如何在 SwiftUI 中显示键盘时显示完整列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在键盘出现时显示完整的列表?键盘隐藏了列表的下部.

How is it possible to show the complete List when the keyboard is showing up? The keyboard is hiding the lower part of the list.

我的列表行中有一个 textField.当键盘出现时,无法向下滚动以查看完整列表.键盘位于列表的前面,而不是列表的下方".这是我的编码:

I have a textField in my list row. When the keyboard shows up it is not possible to scroll down to see the complete list. The keyboard is in front of the list and not "under" the list. This is my coding:

struct ContentView: View {

    @State private var name = ""

    var body: some View {
        List {
            VStack {
                Text("Begin")
                    .frame(width: UIScreen.main.bounds.width)
                    .padding(.bottom, 400)
                    .background(Color.red)

                TextField($name, placeholder: Text("enter text"), onEditingChanged: { _ in
                    //
                }) {
                    //
                }

                Text("End")
                    .frame(width: UIScreen.main.bounds.width)
                    .padding(.top, 400)
                    .background(Color.green)
            }
            .listRowInsets(EdgeInsets())
        }
    }
}

谁能帮助我如何做到这一点?

Can anybody help me how I can do this?

非常感谢.

推荐答案

有一个 在此处回答来处理键盘操作,您可以订阅这样的键盘事件:

there is an answer here to handle keyboard actions, you can subscribe for keyboard events like this:

final class KeyboardResponder: BindableObject {
    let didChange = PassthroughSubject<CGFloat, Never>()
    private var _center: NotificationCenter
    private(set) var currentHeight: CGFloat = 0 {
        didSet {
            didChange.send(currentHeight)
        }
    }

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

然后像这样使用它:

@State var keyboard = KeyboardResponder()
var body: some View {
        List {
            VStack {
             ...
             ...
             ...
            }.padding(.bottom, keyboard.currentHeight)
}

这篇关于如何在 SwiftUI 中显示键盘时显示完整列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆