在SwiftUI中显示键盘时如何显示完整列表

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

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

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

}

}

}

有人可以帮我怎么做吗?

非常感谢你。

回答:

这里有一个处理键盘操作的,您可以订阅这样的键盘事件:

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中显示键盘时如何显示完整列表 的全部内容, 来源链接: utcz.com/qa/401532.html

回到顶部