I've got an array of items that I use as a source of truth, and I copy that array into another array (filteredItems) and use that to power a NavigationSplitView (on MacOS).
I can sort the items in filteredItems by create date, title, last modified date, forward and reverse, no problem. And I have a text filter field that I can use to filter out items in the filteredItems field and that works great.
So far so good.
But if I reduce the filter text or remove it altogether—thus increasing the number of items in filteredItems or returning it to its original state—weird things happen.
Clicking on items in the navigation portion of the view doesn't bring up the detail view as it did before the reduction and re-adding of items.
After clicking on several of the non-responsive nav items, it freezes up.
I know there are different ways to do this, but my view is set up like this:
NigationSplitView {
// filter tool, etc.
List {
ForEach(ascending ? filteredItems : filteredItems.reversed()) { item in
NavigationLink {
ItemView(item: item)
} label: {
// yadda yadda
}
}
}
(ascending is just a boolean state variable)
I know there's not much detail here, but I should be able to change filteredItems as much as I want, right? Or is this construct wrong?
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
Hello!
Is it possible to disable animation which appeared in iOS 18 when switching tab items?
I only found a solution for UIKit: https://forums.developer.apple.com/forums/thread/763122.
Whenever I start editing TextField or while editing TextField, Xcode shows this worning, and takes a few seconds to show the keyboard.
There is no 'availabilityDetailedInfo' in my source code, and I could not find similar errors on the internet.
Can't find or decode availabilityDetailedInfo
unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo
Can't find or decode reasons
unavailableReasonsHelper: Failed to get or decode unavailable reasons as well
Can't find or decode availabilityDetailedInfo
unavailableReasonsHelper: Failed to get or decode availabilityDetailedInfo
Can't find or decode reasons
unavailableReasonsHelper: Failed to get or decode unavailable reasons as well
I tried building the View from this section, but when there is a List on the second tab, the animation performed by the matchedGeometryEffect does not work as intended.
This video shows how the transition works with Text("Second Tab") as the second tab. Everything looks fine.
But when I replace the Text with a List, the transition flickers and does not look smooth anymore.
List {
Text("The Scarlet Letter")
Text("Moby-****")
Text("Little Women")
Text("Adventures of ")
}
Here is the code for the app.
import SwiftUI
@main
struct MyWatchApp: App {
@Namespace var library
@State var pageNumber = 0
private let bookIcon = "bookIcon"
var body: some Scene {
WindowGroup {
NavigationStack {
TabView(selection: $pageNumber) {
VStack {
Image(systemName: "books.vertical.fill")
.imageScale(.large)
.matchedGeometryEffect(
id: bookIcon,
in: library,
properties: .frame,
isSource: pageNumber == 0)
Text("Books")
}
.tag(0)
Text("Second Tab").tag(1)
}
.tabViewStyle(.verticalPage)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Image(systemName: "books.vertical.fill")
.matchedGeometryEffect(
id: bookIcon,
in: library,
properties: .frame,
isSource: pageNumber != 0)
}
}
}
}
}
}
I tried the example from https://developer.apple.com/documentation/swiftui/editmode. It's not working for me.
struct ContentView: View {
@Environment(\.editMode)
private var editMode
@State
private var name = "Maria Ruiz"
var body: some View {
NavigationView {
Form {
Text(String(editMode!.wrappedValue.isEditing))
if editMode?.wrappedValue.isEditing == true {
TextField("Name", text: $name)
} else {
Text("test")
}
}
.animation(nil, value: editMode?.wrappedValue)
.toolbar { // Assumes embedding this view in a NavigationView.
EditButton()
}
}
}
}
It shows the texts "false" and "test", before and after clicking Edit. What am I missing? I'm using XCode 14.0.1 and the deployment target is iOS 16. I also tried on a real iPhone and on iOS 15.5 in the Simulator. Thanks for any help.
I'm trying to use the iOS 18 translation feature which works fine if I scroll slowly, but run into fatal errors when I scroll quickly.
In my view, I have this state property:
@State private var translationConfiguration: TranslationSession.Configuration?
In the body, I attach a .translationTask closure to the top-level view:
.translationTask(translationConfiguration) { translationSession in
Task { @MainActor in
...
let response = try await translationSession.translate(originalContent) // this line causes the fatal error.
}
}
I also have an onAppear { } closure on the same top-level view, which sets translationConfiguration if it is nil, or calls translationConfiguration?.invalidate() if it's non-nil.
When I scroll quickly, the view presumably appears and disappears quickly, but it seems that the translationTask closure still runs after the view disappears.
I get this fatal error:
Translation/TranslationError+TranslationOnly.swift:54: Fatal error: Attempted to use TranslationSession after the view it was attached to has disappeared, which is not supported. Instead of storing a TranslationSession instance outside of the .translationTask closure, trigger a .translationTask to run again on a visible view and use that TranslationSession instance.
The recommendation from the error message seems incorrect, though. I am not using the TranslationSession instance outside of the translationTask closure. I'm using it only inside of it.
I tried to keep an extra visible boolean property that gets set to true when the onAppear closure is called, and set to false when the onDisappear closure is called, and then I guard on that within the translationTask, but that doesn't fix the issue.
What am I missing?
Hi there!
I’m experiencing an issue while loading images with Kingfisher in a LazyVStack containing around 500 items. When I use low-resolution images, everything loads correctly. However, when I switch to higher quality images, only some of them load successfully, while the rest remain stuck in a loading state, and I see the following log:
nw_connection_add_timestamp_locked_on_nw_queue [C1] Hit maximum timestamp count, will start dropping events
Interestingly, if I switch from WiFi to 5G, the images start loading again, but the loading stalls once more after a few additional images.
Could you help me understand why this happens with high-quality images and how to resolve it?
Thank you!
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink.
I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze.
https://developer.apple.com/forums/thread/708592?page=1#736374022
has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
I just tried the "Building a document-based app with SwiftUI" sample code for iOS 18.
https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui
I can create a document and then close it. But once I open it back up, I can't navigate back to the documents browser. It also struggles to open documents (I would tap multiple times and nothing happens). This happens on both simulator and device.
Will file a bug, but anyone know of a work-around? I can't use a document browser that is this broken.
I'm adding widget interactivity to my home screen widgets via buttons and AppIntents, but running into some interesting behavior the way the timeline is reloaded after.
I'm following this guide from Apple
https://developer.apple.com/documentation/widgetkit/adding-interactivity-to-widgets-and-live-activities
And the widget is guaranteed to be reloaded when a button pressed with an intent, But whenever the AppIntent is done with the perform action, the widget timeline is always reloaded twice. It's also interesting to note that both reloads happen after the perform method. If you add a 10 second sleep in the perform, nothing happens for 10 seconds, then both reloads happen.
This issue with this is 2-fold.
calculating and rendering the entire widget timeline can be Networking and DB intensive operations, so I would ideally like to avoid doing all the work twice and save the users battery and processing.
The even worse issue, sometimes data on the server changes in between the split second duplicate widget timeline reloads, causing the widget to flash one state, then update to another a second later which is not a good user experience.
I have a sample project which shows the issue and is very easy to reproduce.
The widget simply keeps track of the number of reloads.
To reproduce:
Add the widget to the homescreen
Press the refresh button, and observe the timeline refresh count always goes up by 2.
I've filed a Feedback and attached the sample project and screen recording for anyone to reproduce.
FB15595835
https://developer.apple.com/documentation/WidgetKit/Adding-interactivity-to-widgets-and-Live-Activities#Add-a-toggle
Before explaining the situation, I referred to this document.
I'm making a widget with a toggle that works with Intent. (To be precise, it's Live Activity, but Apple's literally toggling and button interaction are implemented in the same way)
If you press the toggle when the device is locked, the toggle represents the state.
However, as described at the top of the same document, the device must be unlocked to execute Intent, so I can't actually change the data.
That's fine, but how can I return the isOn of the toggle to false? I'm blocked here because no code is executed.
If it is a widget in the home screen, it will be basically unlocked, so I can proceed according to the method of the document, but if it is today's view, user can access it even if device is locked.
I tested it in today's view with the Reminders app, If I don't unlock the device after tapping the toggle it returns the toggle back to false state.
I wonder how I can achieve this.
Is there an API that I missed?
Summary.
Tap the toggle of the widget while the device is locked.
The device waits for unlocking, but the user cancels it without unlocking it. (Still locked)
Return the isOn of the toggle to false. <- The part I want.
We have recently added WidgetKit widgets to an existing product, and they've been working great on Macs using Big Sur and later. Recently, when installing a build on a Montery Mac, the widgets were no longer in Notification Center. After some trial and error, we discovered that if we build the project with Xcode 15.4, the widgets appear, but if we build with Xcode 16, the widgets vanish. This seems to happen on Macs running Big Sur or Monterey. The project is being built on Macs running Sonoma (both Apple Silicon and Intel).
Is there a build setting in Xcode 16 that may have this effect?
Hello.
We have multiple WidgetKit extensions in our application. in IOS18 there is option to transform app icon into widget by long press on icon.
Is there any way to setup default WidgetKit extension that icon will be transformed to?
Hello,
I am trying to create a custom control with the new WidgetKit control widget APIs.
In my custom control, I want to display a custom image, in fact a custom symbol. The custom symbol is not displayed with latest iOS 18 Seed 7 (22A5346a). Only system symbols are displayed. I don't find any information about it in the WidgetKit Apple Developer Documentation.
ControlWidgetButton(action: MyIntent()){
Label(title: {
Text("My Custom Control")
}, icon: {
Image("mycustomsymbol") //NOT DISPLAYED
// Image(systemName: "rectangle.portrait.inset.filled") IS DISPLAYED
})
}
There was no issue with custom symbols in beta 4. Now since beta 5, custom symbols are not displayed.
I wonder if this is a bug or this is intended.
Can you help me ?
I filed a feedback FB14888220
Thank you
Hello community,
I'm an iOS developer from VW group, I was doing some proof of concepts around an automaker app, and I've found a big blocker. When I was trying to summon a keyboard, it wasn't displayed.
So is it even possible?
Do I have to do some workaround with Carplay templates in order to be able to have the native keyboard from Carplay, or is there a special component that I need to introduce in my code to summon the keyboard?
Thank you very much.
David Cosialls.
It seems somewhere around the update to xcode 16 and swift 6, apple may have decided to change when view are initialized. My views suddenly pre-initialize before opening the view. Is this a new feature?
I have a regular VStack or a LazyVStack, with ForEach and navigationLinks inside. Those views that the navigation link takes you to are initializing as I am scrolling in the VStack. This is absurd, there is so much overhead going on in these views to be initialized. I can think of a fix which is to implement init functions in the onAppear, and keep a property to track if view already appeared. But before that I just want to make sure this is a new feature and not some mishap on my part, and if there is a way to disable it.
Thank you.
I'm having trouble getting the "Save to Files" option to work with ShareLink. Here's a simple example:
struct Item: Transferable {
public static var transferRepresentation: some TransferRepresentation {
FileRepresentation(exportedContentType: .jpeg) { item in
// Write a jpeg to disk
let url = URL.documentsDirectory.appending(path: "item.jpeg")
let jpegData = UIImage(named: "testImg")!.jpegData(compressionQuality: 1)!
try! jpegData.write(to: url)
return SentTransferredFile(url)
}
}
}
struct ContentView: View {
var body: some View {
ShareLink(item: Item(), preview: SharePreview("Test Item"))
}
}
The ShareSheet presents all of the usual options, but tapping "Save to Files" briefly presents an empty modal before immediately dismissing.
The following errors are logged to the console:
2022-09-12 14:19:57.481592-0700 ExportTest[3468:1374472] [NSExtension] Extension request contains input items but the extension point does not specify a set of allowed payload classes. The extension point's NSExtensionContext subclass must implement `+_allowedItemPayloadClasses`. This must return the set of allowed NSExtensionItem payload classes. In future, this request will fail with an error.
2022-09-12 14:19:58.047009-0700 ExportTest[3468:1374472] [ShareSheet] cancelled request - error: The operation couldn’t be completed. Invalid argument
Sharing finished with error: Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" at SwiftUI/SharingActivityPickerBridge.swift:266
2022-09-12 14:19:58.584374-0700 ExportTest[3468:1379359] [AXRuntimeCommon] AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:3472 (
0 AXRuntime 0x00000001ca77b024 _AXGetPortFromCache + 932
1 AXRuntime 0x00000001ca77d1d8 AXUIElementPerformFencedActionWithValue + 772
2 UIKit 0x00000002258b3284 3CB83860-AA42-3F9A-9B6E-2954BACE3DAC + 778884
3 libdispatch.dylib 0x0000000105078598 _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x000000010507a04c _dispatch_client_callout + 20
5 libdispatch.dylib 0x00000001050820fc _dispatch_lane_serial_drain + 988
6 libdispatch.dylib 0x0000000105082e24 _dispatch_lane_invoke + 420
7 libdispatch.dylib 0x000000010508fcac _dispatch_workloop_worker_thread + 740
8 libsystem_pthread.dylib 0x00000001ed9e8df8 _pthread_wqthread + 288
9 libsystem_pthread.dylib 0x00000001ed9e8b98 start_wqthread + 8
)
Additionally, this error is logged when the ShareSheet is first presented (before tapping Save to Files):
[ShareSheet] Couldn't load file URL for Collaboration Item Provider:<NSItemProvider: 0x282a1d650> {types = (
"public.jpeg"
)} : (null)
Has anybody had luck getting custom Transferable representations to work with ShareLink?
I would like to implement the same kind of behavior as the Dropoverapp application, specifically being able to perform a specific action when files are dragged (such as opening a window, for example).
I have written the code below to capture the mouse coordinates, drag, drop, and click globally. However, I don't know how to determine the nature of what is being dropped. Do you have any ideas on how to detect the nature of what is being dragged outside the application's scope?
Here is my current code:
import SwiftUI
import CoreGraphics
struct ContentView: View {
@State private var mouseX: CGFloat = 0.0
@State private var mouseY: CGFloat = 0.0
@State private var isClicked: Bool = false
@State private var isDragging: Bool = false
private var mouseTracker = MouseTracker.shared
var body: some View {
VStack {
Text("Mouse coordinates: \(mouseX, specifier: "%.2f"), \(mouseY, specifier: "%.2f")")
.padding()
Text(isClicked ? "Mouse is clicked" : "Mouse is not clicked")
.padding()
Text(isDragging ? "Mouse is dragging" : "Mouse is not dragging")
.padding()
}
.frame(width: 400, height: 200)
.onAppear {
mouseTracker.startTracking { newMouseX, newMouseY, newIsClicked, newIsDragging in
self.mouseX = newMouseX
self.mouseY = newMouseY
self.isClicked = newIsClicked
self.isDragging = newIsDragging
}
}
}
}
class MouseTracker {
static let shared = MouseTracker()
private var eventTap: CFMachPort?
private var runLoopSource: CFRunLoopSource?
private var isClicked: Bool = false
private var isDragging: Bool = false
private var callback: ((CGFloat, CGFloat, Bool, Bool) -> Void)?
func startTracking(callback: @escaping (CGFloat, CGFloat, Bool, Bool) -> Void) {
self.callback = callback
let mask: CGEventMask = (1 << CGEventType.mouseMoved.rawValue) |
(1 << CGEventType.leftMouseDown.rawValue) |
(1 << CGEventType.leftMouseUp.rawValue) |
(1 << CGEventType.leftMouseDragged.rawValue)
// Pass 'self' via 'userInfo'
let selfPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
guard let eventTap = CGEvent.tapCreate(
tap: .cghidEventTap,
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: mask,
callback: MouseTracker.mouseEventCallback,
userInfo: selfPointer
) else {
print("Failed to create event tap")
return
}
self.eventTap = eventTap
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
CGEvent.tapEnable(tap: eventTap, enable: true)
}
// Static callback function
private static let mouseEventCallback: CGEventTapCallBack = { _, eventType, event, userInfo in
guard let userInfo = userInfo else {
return Unmanaged.passUnretained(event)
}
// Retrieve the instance of MouseTracker from userInfo
let tracker = Unmanaged<MouseTracker>.fromOpaque(userInfo).takeUnretainedValue()
let location = NSEvent.mouseLocation
// Update the click and drag state
switch eventType {
case .leftMouseDown:
tracker.isClicked = true
tracker.isDragging = false
case .leftMouseUp:
tracker.isClicked = false
tracker.isDragging = false
case .leftMouseDragged:
tracker.isDragging = true
default:
break
}
// Call the callback on the main thread
DispatchQueue.main.async {
tracker.callback?(location.x, location.y, tracker.isClicked, tracker.isDragging)
}
return Unmanaged.passUnretained(event)
}
}
Hi,
When using SwiftUI ‘List’ with a large number of elements (4000+), I noticed a significant performance issue if extracting the views inside the ‘ForEach’ block into their own subview class. It affects scrolling performance, and using the scroll handle in the scrollbar causes stutters and beachballs. This seems to happen on macOS only ... the same project works fine on iOS.
Here's an example of what I mean:
List (selection: $multiSelectedContacts) {
ForEach(items) { item in
// 1. this subview is the problem ... replace it with the contents of the subview, and it works fine
PlainContentItemView(item: item)
// 2. Uncomment this part for it to work fine (and comment out PlainContentItemView above)
/*HStack {
if let timestamp = item.timestamp, let itemNumber = item.itemNumber {
Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)")
}
}*/
}
}
struct PlainContentItemView: View {
let item: Item
var body: some View {
HStack {
if let timestamp = item.timestamp, let itemNumber = item.itemNumber {
Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)")
}
}
}
}
Item is a NSManagedObject subclass, and conforms to Identifiable by using the objectID string value.
With this, scrolling up and down using the scrolling handle, causes stuttering scrolling and can beachball on my machine (MacBook Pro M1).
If I comment out the ‘PlainContentItemView’ and just use the HStack directly (which is what was extracted to ‘PlainContentItemView’), the performance noticeably improves, and I can scroll up and down smoothly.
Is this just a bug with SwiftUI, and/or can I do something to improve this?
The interactiveDismissDisabled() function in SwiftUI's Sheet no longer works as expected in iOS 18.1 (22B83). It was working as expected until iOS 18.0.1.
Are there any other users experiencing the same issue?
struct ContentView: View {
@State private var openSheet = false
var body: some View {
NavigationStack {
Button("Open") {
openSheet = true
}
.sheet(isPresented: $openSheet) {
SheetView()
}
}
}
}
struct SheetView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
Text("This is the Sheet")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
}
.interactiveDismissDisabled()
}
}
}
Supplementary information: In iOS 18.1, even Apple's native Journal app allows users to swipe-to-dismiss the sheet when creating a new entry. Previously, a confirmation dialog would be displayed, but this is no longer the case.