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

查看:129
本文介绍了在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天全站免登陆