I gave the FocusCookbook sample project a try and FocusState is not working correctly on iOS 18. I understand the sample was originally designed for iOS 17 when it was released along side the WWDC 2023 talk The SwiftUI Cookbook for Focus. however I am suprised it no longer works on iOS 18.
E.g. when I launch the app on iPhone 16 Pro simulator (Xcode 16.2, iOS 18.2 Simulator) and tap the grocery list nav bar button, the grocery sheet appears however the last entry text field is not focused like .defaultFocus
is designed to do.
Futhermore, if I tap the add (+) button and a new entry is added, despite the addEmptyItem()
func setting the currentItemID
which is the @FocusState var
the focus does not change to the new text field.
Is FocusState broken on iOS 18?
Relevant code from GroceryListView.swift
import SwiftUI
struct GroceryListView: View {
@Environment(\.dismiss) private var dismiss
@Binding var list: GroceryList
@FocusState private var currentItemID: GroceryList.Item.ID?
var body: some View {
List($list.items) { $item in
HStack {
Toggle("Obtained", isOn: $item.isObtained)
TextField("Item Name", text: $item.name)
.onSubmit { addEmptyItem() }
.focused($currentItemID, equals: item.id)
}
}
.toolbar {
ToolbarItem(placement: .cancellationAction) {
doneButton
}
ToolbarItem(placement: .primaryAction) {
newItemButton
}
}
.defaultFocus($currentItemID, list.items.last?.id)
}
// MARK: New item
private func addEmptyItem() {
let newItem = list.addItem()
currentItemID = newItem.id
}
private var newItemButton: some View {
Button {
addEmptyItem()
} label: {
Label("New Item", systemImage: "plus")
}
}
private var doneButton: some View {
Button {
dismiss()
} label: {
Text("Done")
}
}
}