I noticed if I show a sheet from a List row, then remove the row the sheet isn't removed from the screen like it is if using VStack or LazyVStack.
I'd be interested to know the reason why the sheet isn't removed from the screen in the code below. It only occurs with List/Form. VStack/LazyVStack gives the expected result. I was wondering if it is an implementation issue, e.g. since List is backed by UICollectionView maybe the cells can't be the presenter of the sheet for some reason.
Launch on iPhone 16 Pro Simulator iOS 18.2
Tap "Show Button"
Tap "Show Sheet"
What is expected:
The sheet should disappear after 5 seconds. And I don't mean it should dismiss, I just mean removed from the screen. Similarly if the View that showed the sheet was re-added and its show @State was still true, then the sheet would be added back to the screen instantly without presentation animation.
What actually happens:
Sheet remains on screen despite the row that presented the sheet being removed.
Xcode 16.2
iOS Simulator 18.2.
struct ContentView: View {
@State var showButton = false
var body: some View {
Button("\(showButton ? "Hide" : "Show" ) Button") {
showButton = true
Task {
try? await Task.sleep(for: .seconds(5))
self.showButton = false
}
}
//LazyVStack { // does not have this problem
List {
if showButton {
SheetButton()
}
}
}
}
struct SheetButton: View {
@State var sheet = false
@State var counter = 0
var body: some View {
Text(counter, format: .number)
Button("\(sheet ? "Hide" : "Show") Sheet") {
counter += 1
sheet.toggle()
}
.sheet(isPresented: $sheet) {
Text("Wait... This should auto-hide in 5 secs. Does not with List but does with LazyVStack.")
Button("Hide") {
sheet = false
}
.presentationDetents([.fraction(0.3)])
}
// .onDisappear { sheet = false } // workaround
}
}
I can work around the problem with .onDisappear { sheet = false } but I would prefer the behaviour to be consistent across the container controls.
Post
Replies
Boosts
Views
Activity
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")
}
}
}
Could an Apple employee that works on SwiftUI please explain the update() func in the DynamicProperty protocol? The docs have ambiguous information, e.g.
"Updates the underlying value of the stored value."
and
"SwiftUI calls this function before rendering a view’s body to ensure the view has the most recent value."
From: https://developer.apple.com/documentation/swiftui/dynamicproperty/update()
How can it both set the underlying value and get the most recent value? What does underlying value mean? What does stored value mean?
E.g. Is the code below correct?
struct MyProperty: DynamicProperty {
var x = 0
mutating func update() {
// get x from external storage
x = storage.loadX()
}
}
Or should it be:
struct MyProperty: DynamicProperty {
let x: Int
init(x: Int) {
self.x = x
}
func update() {
// set x on external storage
storage.save(x: x)
}
}
This has always been a mystery to me because of the ambigious docs so thought it was time to post a question.
Is it normal behaviour that when I apply a .toolbar to a Group that I see duplicate buttons equal to the number of Views in the Group? e.g.
Group {
Text("1")
Text("2")
Text("3")
}
.toolbar {
Button("Hi") {
}
}
Results in 3 toolbar buttons appearing in the UI, like in this screenshot:
If not, then I'll submit feedback about this bug but thought I'd ask first.
Xcode Version 16.0 beta 6 (16A5230g)
iPhone 15 Pro Simulator
Please delete this one!
I noticed the code snippets are missing from the wwdc2024 10210 video titled Bring your app’s core features to users with App Intents https://developer.apple.com/videos/play/wwdc2024/10210/ It would be useful if those could be added. I also noticed the transcript is missing from the web version but it is in the Developer app, that is odd.
I was wondering if anyone knows why the sample project uses Task.detached everywhere because it seems highly non-standard, e.g. in ContentView:
.task {
Task.detached { @MainActor in
await flightData.load()
}
}
Instead, I would expect to see something like:
.task {
flightData = await controller.loadFlightData()
}
Or:
.task {
await controller.load(flightData: flightData)
}
Is the use of detached perhaps an attempt to work around some issue with ObservableObject published updates?
If they had used .task they could have removed the class LocationsHandler: ObservableObject and simply done:
struct ContentView: View {
@State var lastLocation: CLLocation?
var body: some View {
VStack {
...
}
.task {
let updates = CLLocationUpdate.liveUpdates()
for try await update in updates {
if let loc = update.location {
self.lastLocation = loc
}
}
}
And saved themselves about 20 or so lines of code. .task was added in the year before so it isn't the case that it wasn't available to the CoreLocation team yet. To wrap async/await in a Combine's ObservableObject is very strange. They could have also used @AppStorage instead of UserDefaults and saved another few lines. To be honest this is some of the strangest SwiftUI code I've seen.
PersistentModel is a protocol but would make more sense as a class that we then subclass. If all of the implementation was in a parent class of our model classes then there wouldn't be all the problems caused by requiring the use of the @Model macro, e.g. default property values not working, unable to subclass, overriding get/set not possible, conflict in property names...
I was wondering if ModelContext's fetch() contains an auto-updating results array? I ask because there is no documentation yet and in the WWDC23 lounge it was suggested by Debbie G to use fetch() to overcome the limitations of @Query i.e. no way to use dynamic filtering or sorting. I suppose we would call fetch() from onAppear and onChanged to support dynamic queries that also have auto-updating of results. Personally I don't understand why @Query and the old @FetchRequest were implemented as property wrappers instead of SwiftUI modifiers, e.g. .fetch(predicate:sort:) to match other modifiers like .task(id:).
I was hoping for it to behave similar to Date's formatted() that returns a locale-aware string that automatically invalidates SwiftUI Text when the locale changes. Although I'm not exactly sure how it works.
If fetch() doesn't auto-update then what would be the point of using it instead of just using NSFetchRequest with dictionary result type to get data into a SwiftUI view struct fast and memory efficient.
I noticed a problem with the NavigationCookbook sample code. The builtInRecipes array containing Recipe models without IDs which means state restoration fails because the recipes have new unique IDs every time the app is launched (there is a let id = UUID() in Recipe). The problem is in NavigationCookbook/Models/DataModel
private let builtInRecipes: [Recipe] = {
var recipes = [
"Apple Pie": Recipe(
name: "Apple Pie", category: .dessert,
ingredients: applePie.ingredients),
Should be
let builtInRecipes: [Recipe] = {
var recipes = [
"Apple Pie": Recipe(
id: UUID(uuidString: "E35A5C9C-F1EA-4B3D-9980-E2240B363AC8")!,
name: "Apple Pie", category: .dessert,
ingredients: Ingredient.fromLines(applePie)),
And the same thing for all the other built-in recipes in the array. The builtInRecipes containing ids can be found in the Code tab in the Developer app for this samples WWDC session video:
https://developer.apple.com/wwdc22/10054
I also submitted this as feedback FB11744612
Hi I would like to show the PhotosPicker programatically the same way we can do with sheet(isPresented: Binding<Bool>) and fullScreenCover(isPresented: Binding<Bool>), i.e. I would like:
photosPicker(isPresented: Binding<Bool>, selectedItem: Binding<PhotosPickerItem?>).
This would allow me to have multiple buttons that show the picker and would make all my code that shows sheets consistent, thanks for reading.
Hi I noticed with CKModifyRecordsOperation, modifyRecordsResultBlock works differently from the now deprecated modifyRecordsCompletionBlock. When using a savePolicy of ifServerRecordUnchanged (which is the default), if the record on the server has been changed since it was downloaded, edited and saved again then modifyRecordsResultBlock unexpectedly does not error. But modifyRecordsCompletionBlock does error which is what I would expect.
The kind of error in this case looks like this:
"Server Record Changed" (14/2004); server message = "client oplock error updating record";
My question is, is this new behavior by design?
By the way, I'm having to write my own async/await version of save records using withTaskCancellationHandler and withCheckedThrowingContinuation because the built-in one does not support task cancellation which I require to use with SwiftUI's .task modifier.
Finally, modifyRecordsResultBlock and the other 2 new ones are missing its documentation because it hasn't used the correct DocC format, it's using old style comments which are not being picked up. FB10400023
In the slides at 11:50 the following code snippet is shown:
.backgroundTask(.urlSession("isStormy")) {
// ...
}
Please could you explain what should be done in this block? The video just cuts off right after and seems like the explanation is missing. Thanks.
The presenter says "you might be wondering why we don't do this with CKReference instead. And that's because CKReference has some limitations that we don't think work well for Core Data clients. Namely that it's limited to 750 total objects."
However, that isn't correct, the 750 limit is only for references that have a delete action:
https://developer.apple.com/documentation/cloudkit/ckrecord/reference
Important
There is a hard limit to the number of references with a CKRecord.ReferenceAction.deleteSelf action that any one record can have. This limit is 750 references, and any attempt to exceed it results in an error from the server.
This is why the Notes app has no issue with more than 750 note records with a reference to a folder record.
I really wish NSPersistentCloudKitContainer had used CKReference and also that _CKReferenceActionValidate was made public. CKShare has limitations too, yet it used that and there was no custom sharing done like custom references were done.