The keyboard lifts the last view in a VStack
.
Adding .ignoresSafeArea(.keyboard)
only to BannerAd
doesn't work. (Why?)
import SwiftUI
import RealmSwift
struct ContentView: View {
@FocusState var focusedId: ObjectId?
var body: some View {
NavigationStack {
VStack {
ItemsView(focusedId: $focusedId)
BannerAd()
}
.ignoresSafeArea(.keyboard)
}
}
}
If I add .ignoresSafeArea(.keyboard)
to the VStack
, the focus state doesn't work for the ItemsView
. (correction: It just registered that the keyboard is simply lifting all views)
import SwiftUI
import RealmSwift
class Item: Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String
}
struct ItemsView: View {
@ObservedResults(Item.self) var items
var focusedId: FocusState<ObjectId?>.Binding
var body: some View {
List {
// Items
ForEach(items) { item in
ItemView(item: item, focusedId: focusedId)
}
.onDelete(perform: $items.remove)
}
.navigationTitle("Items")
.toolbar {
// Add
ToolbarItem(placement: .navigationBarTrailing) {
Button {
let item = Item()
$items.append(item)
focusedId.wrappedValue = item._id
} label: {
Label("Add item", systemImage: "plus")
}
}
// Quick add
ToolbarItem(placement: .principal) {
Button {
for i in 0...50 {
let item = Item()
item.name = "Item \(i)"
$items.append(item)
}
} label: {
Text("Add multiple items")
}
}
// Delete
ToolbarItem(placement: .navigationBarLeading) {
Button(role: .destructive){
$items.remove(atOffsets: IndexSet(integersIn: items.indices))
} label: {
Label("Delete all", systemImage: "trash")
}
}
}
}
}
struct ItemView: View {
@ObservedRealmObject var item: Item
var focusedId: FocusState<ObjectId?>.Binding
var body: some View {
TextField("Item", text: $item.name)
.focused(focusedId, equals: item._id) // focus
}
}
import SwiftUI
struct BannerAd: View {
var body: some View {
Text("Banner ad")
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
}
}
Is there an easy way to ignore safe area only for BannerAd
?