ScrollView
キーボードが表示されたときにコンテンツがスクロールできるように、キーボードのサイズの下パディングを追加して設定する必要があります。
NotificationCenter
キーボードのサイズを取得するには、 を使用して、keyboards イベントに登録する必要があります。これを行うには、カスタム クラスを使用できます。
import SwiftUI
import Combine
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) {
print("keyboard will show")
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
currentHeight = keyboardSize.height
}
}
@objc func keyBoardWillHide(notification: Notification) {
print("keyboard will hide")
currentHeight = 0
}
}
BindableObject
適合により、このクラスを として使用し、ビューの更新をトリガーすることができますState
。必要に応じて、SwiftUI チュートリアルのチュートリアルを参照してBindableObject
ください。
それを取得したらScrollView
、キーボードが表示されたときにそのサイズを縮小するように構成する必要があります。便宜上、これScrollView
をある種のコンポーネントにラップしました。
struct KeyboardScrollView<Content: View>: View {
@State var keyboard = KeyboardResponder()
private var content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
ScrollView {
VStack {
content
}
}
.padding(.bottom, keyboard.currentHeight)
}
}
あとは、コンテンツを custom 内に埋め込むだけですScrollView
。
struct ContentView : View {
@State var textfieldText: String = ""
var body: some View {
KeyboardScrollView {
ForEach(0...10) { index in
TextField(self.$textfieldText, placeholder: Text("TextField\(index)")) {
// Hide keyboard when uses tap return button on keyboard.
self.endEditing(true)
}
}
}
}
private func endEditing(_ force: Bool) {
UIApplication.shared.keyWindow?.endEditing(true)
}
}
編集:
キーボードが隠れているときのスクロール動作は本当に奇妙です。padding
アニメーションを使用してパディングを更新すると、これが修正されるか、スクロール ビューのサイズを調整する以外のものを使用することを検討する必要があります。