Code example:
//
// ListSafeAreaBarKeyboardTextField.swift
// Exploration
import SwiftUI
import Foundation
struct ListSafeAreaBarKeyboardTextField: View {
@State private var typedText: String = ""
@FocusState private var focusingTextField: Bool
private let items = Array(1...16)
var body: some View {
ScrollViewReader { proxy in
List(items, id: \.self) { number in
Text("Item \(number)")
.id(number)
}
.onAppear {
if let lastItem = items.last {
proxy.scrollTo(lastItem, anchor: .bottom)
}
}
.onChange(of: focusingTextField) { oldValue, newValue in
// This simply won't work
// ~ 12th - 16th item will still get covered by keyboard
if newValue == true {
// Delay to allow keyboard animation to complete
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if let lastItem = items.last {
withAnimation {
proxy.scrollTo(lastItem, anchor: .top)
}
}
}
}
}
}
.scrollDismissesKeyboard(.interactively)
.safeAreaBar(edge: .bottom) {
TextField("Type here", text: $typedText, axis: .vertical)
.focused($focusingTextField)
// Design
.padding(.horizontal, 16)
.padding(.vertical, 10)
.glassEffect()
// Paddings
.padding(.horizontal, 24)
.padding(.vertical, 12)
}
}
}