Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

Widget Configuration Search with group headers...
I am working on a widget that allows the user to specify a list of items. Each item is an AppEntity and has an id, a type and a name. In the DisplayRepresentation I have and icon / image for each type. So when I tap on the specified items option a list of user specified items comes up with the option to search, select, deselect items. This works nicely. I sort them suggested entities by type then name so the list is predictable. How would like to be able to have a group / type header for each type of item. However, I don't know how to do that with the AppEntities. Help would be appreciated. I noticed that HomeKit takes a different approach. They have a list of items at the bottom labeled "Choose Scene Or Accessory". You can move the items up / down in the list, you can delete, and add items. When you tap "Add an item" in the list it goes to a search screen where the items are grouped by the room and have the individual items beneath them. I don't like that you have to select one item at a time but I love having the headings for the rooms. The question here is how did they do that? Is there sample code somewhere that does something similar.
1
0
80
3w
Resolving AppIntent in the app from a widget...
Is anyone familiar with AppIntents and their usage? I have an AppIntent defined in my widget extension. I have the same AppIntent defined in the app marked as ForegroundContinuableIntent. If I add the intent on a SwiftUI button and tap the Button it correctly resolves the app's version of the intent and performs that intent. However, what I really want to do is perform the AppIntent manually as the timeline updates but not more often than every hour (i.e. >= 1 hour). It's easy enough to handle the timing in the timeline. However, I do not know how to resolve the intent such that it calls the app's version of the intent (i.e. the same way that a Button does). If I just call perform it will run the version in the widget extension. The end goal is to minimally / periodically sync with the app. Thanks in advance for any help / advice on this.
Topic: UI Frameworks SubTopic: SwiftUI
3
0
109
4w
PKPass Framework
I am trying to work with the data inside the barcode string in shared PKPass. The documentation shows that is should look for @property (nonatomic, readonly, nullable) PKBarcode *primaryBarcode; I have tried to use it like this guard let code = pass.primaryBarcode?.message else { return } I get a constant message that PKPass has no member primaryBarcode The PKPass.h file in my IOS SDK does not seem to include the @property primaryBarcode or @property barcode. I am running Xcode 16.4 (16F6) and my app target is 17.6 + Is there a restriction on this property? I cannot find an SDK later than mine - the App Store does not offer one. I am unsure of this is a public or private issue - does anyone know? Thanks for reading this. Max
Topic: UI Frameworks SubTopic: SwiftUI
0
0
68
4w
Shouldn't SwiftUI only re-renders if var is used on view?
Why is the SwiftUI re-render the UI event if the view does not use the counter like in the example bellow...shouldn't SwiftUI framework be smart enough to detect that?? import SwiftUI class ViewModel: ObservableObject { @Published var counter: Int = 0 // Not used in the view's body @Published var displayText: String = "Hello" // Used in the view's body } struct ContentView: View { @StateObject private var viewModel = ViewModel() var body: some View { VStack { Text(viewModel.displayText) // Depends on displayText } .onChange(of: viewModel.counter) { newValue in print("Counter changed to: \(newValue)") } } } Is there any solution more elegant without using Publishers??
2
0
109
May ’25
Live activity widget not updated locally after server update
I am using live activity in my app. Functionality is start, update & end events are started from the server. There is one interaction button added using app intent in live activity widget. That button needs to update widget ui locally using activity kit. Issue is when os receives first start event push then update ui works fine and reflecting on live activity widget but when update notification receives by os after 1 mins then action button stops updating the ui locally. Can anyone please add some suggestions to fix this.
0
0
82
May ’25
How can I make a new item from within a navigationlink?
Sorry if this is too basic, but I really can't figure out how to make this work. I am trying to make a journal app and I want to have a button that creates a new journalentry and then loads it. This code snippet (I removed irrelevant bits) shows how I'm trying to go about it. Basically, the newEntryButtons should launch a JournalPromptRoute for one of the different options: that's the method argument. But putting .createNewEntry() inside the argument means that new entries are being constantly created. I want the system to create a new entry once on the button press and then go to it from the navigationDestination area. Can anyone please explain to me how this is supposed to work? I believe the code snippet is detailed enough to get the point across but please let me know if you need more info. case library case blank(entry: Entry) case mystery case summary(entry: Entry) case entry(entry: Entry) } struct JournalHome: View { @ObservedObject var viewModel: JournalViewModel var mainContent: some View { ScrollView { newEntryButtons LazyVStack { ForEach(filteredEntries) { entry in NavigationLink( value: JournalPromptRoute.entry(entry: entry) ) { JournalCard(entry) } } } } } var body: some View { NavigationStack(path: $path) { mainContent .navigationDestination(for: JournalPromptRoute.self) { route in switch route { case .blank(let entry): JournalEntryView( entry: entry, index: 0, viewModel: viewModel ) } } } } var newEntryButtons: some View { ScrollView(.horizontal) { HStack(spacing: 15) { EntryButton( description: "Add blank entry", method: JournalPromptRoute.blank(entry: viewModel.createNewEntry()), viewModel: viewModel, path: $path ) EntryButton( description: "Select a Journey", method: JournalPromptRoute.library, viewModel: viewModel, path: $path ) EntryButton( description: "Let the Journey find you", method: JournalPromptRoute.mystery, viewModel: viewModel, path: $path ) } } } }
Topic: UI Frameworks SubTopic: SwiftUI
2
0
53
May ’25
Canvas Preview: Cannot preview in this file
Hi, I want to follow the SwiftUI tutorials from Apple Developer. After creating the “Landmarks” app and clicking on ContentView, the preview shows: Cannot preview in this file Failed to launch net.bayerthomas.Landmarks with the Diagnostics: == PREVIEW UPDATE ERROR: FailedToLaunchAppError: Failed to launch net.bayerthomas.Landmarks ================================== | [Remote] JITError | | ================================== | | | [Remote] CouldNotLoadInputObjectFile: Could not load object file during preview: /Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o | | | | path: /Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o | | | | ================================== | | | | | [Remote] XOJITError | | | | | | XOJITError: '/Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o': No such file or directory I am on a fresh install of Xcode 16.3 on macOS 15.4.1. Why is the official tutorial from Apple not working?
Topic: UI Frameworks SubTopic: SwiftUI
1
0
57
May ’25
Crash due to likely infinitely recursive call in SwiftUI `Color.Resolved.init`
So I'm dealing with a really obtuse crash that appears to be a stack overflow in an internal SwiftUI code path creating a Color.Resolved. I haven't found anyone one else with this issue online, and I cannot get it to reproduce on my own device. Interestingly enough, it is only happening on 1 device in the field (according to XCode crash logs). Here are some lines from the crashed thread. You can see that my code is never called, and it appears to be starting in some Array equality check checking the equality of colors (which I can't think of anywhere in my app I am doing anyway). You can see from this trace here that it appears to be a recursive call through Color.Resolved and NSColor.withColorAppearance. I don't have any idea how to solve this, but it keeps happening with at least one in-the-field device across multiple app updates. So my whole app is open source on github at https://github.com/msdrigg/roam, but I don't even use NSColor explicitly anywhere except for here which doesn't match the stack trace. I also tried changing the accent color of the app with defaults write com.msdrigg.roam AppleAccentColor -integer 1 to see if that somehow caused the crash, but my app opened up totally fine (and respected the change). Besides this, the only places I think I could be using dynamic colors is I when define an AccentColor and a WidgetBackground color for my app using xcassets, and then I use these colors from SwiftUI. In most of my app I stick to the system colors (Color.gray and such). Thread 0 Crashed: 0 libsystem_pthread.dylib 0x000000018601213c ___chkstk_darwin + 60 1 CoreFoundation 0x0000000186108434 -[NSArray isEqualToArray:] + 52 (NSArray.m:454) 2 AppKit 0x000000018a21fcd4 -[NSCoreUICatalogColor resolvedCUINamedColorForAppearance:] + 164 (NSColor.m:5057) 3 AppKit 0x0000000189c32cd4 -[NSCoreUICatalogColor resolvedColor] + 48 (NSColor.m:5148) 4 AppKit 0x0000000189c31e74 -[NSDynamicNamedColor colorUsingColorSpace:] + 32 (NSColor.m:4410) 5 SwiftUICore 0x0000000221ca9fd8 CoreColorPlatformColorGetComponents + 116 (CoreColorFunctions.m:149) 6 SwiftUICore 0x0000000221faaf28 specialized Color.Resolved.init(platformColor:) + 92 (CoreColor.swift:14) 7 SwiftUICore 0x0000000221faa5b0 Color.Resolved.init(platformColor:) + 16 (<compiler-generated>:0) 8 SwiftUI 0x00000001b53b1dc4 closure #1 in NSColor.resolve(in:) + 20 (AppKitColorConversions.swift:156) 9 SwiftUI 0x00000001b53b222c partial apply for closure #1 in static NSColor.withColorAppearance(in:_:) + 32 (<compiler-generated>:0) 10 SwiftUI 0x00000001b46b1e54 closure #1 in SubmitTriggerSource.dispatchUpdate(_:) + 28 (PlatformViewCoordinator.swift:12) 11 SwiftUI 0x00000001b5484488 thunk for @escaping @callee_guaranteed () -> () + 28 (<compiler-generated>:0) 12 AppKit 0x0000000189c174a4 +[NSAppearance _performWithCurrentAppearance:usingBlock:] + 72 (NSAppearance.m:2408) 13 SwiftUI 0x00000001b53b2088 specialized static NSColor.withColorAppearance(in:_:) + 324 (AppKitColorConversions.swift:142) 14 SwiftUI 0x00000001b53b1e7c protocol witness for ColorProvider.resolve(in:) in conformance NSColor + 68 (<compiler-generated>:151) 15 SwiftUICore 0x0000000222436e6c ColorBox.resolve(in:) + 124 (Color.swift:288) 16 SwiftUICore 0x0000000222435e30 Color.resolve(in:) + 72 (Color.swift:87) 17 SwiftUI 0x00000001b53b1c88 closure #1 in NSColor.init(_:) + 196 (AppKitColorConversions.swift:124) 18 SwiftUI 0x00000001b4542714 thunk for @escaping @callee_guaranteed (@guaranteed NSAppearance) -> (@owned NSColor) + 56 (<compiler-generated>:0) 19 AppKit 0x0000000189c31e74 -[NSDynamicNamedColor colorUsingColorSpace:] + 32 (NSColor.m:4410) //// ... Repeating for 500 lines 500 SwiftUICore 0x0000000221ca9fd8 CoreColorPlatformColorGetComponents + 116 (CoreColorFunctions.m:149) 501 SwiftUICore 0x0000000221faaf28 specialized Color.Resolved.init(platformColor:) + 92 (CoreColor.swift:14) 502 SwiftUICore 0x0000000221faa5b0 Color.Resolved.init(platformColor:) + 16 (<compiler-generated>:0) 503 SwiftUI 0x00000001b53b1dc4 closure #1 in NSColor.resolve(in:) + 20 (AppKitColorConversions.swift:156) 504 SwiftUI 0x00000001b53b222c partial apply for closure #1 in static NSColor.withColorAppearance(in:_:) + 32 (<compiler-generated>:0) 505 SwiftUI 0x00000001b46b1e54 closure #1 in SubmitTriggerSource.dispatchUpdate(_:) + 28 (PlatformViewCoordinator.swift:12) 506 SwiftUI 0x00000001b5484488 thunk for @escaping @callee_guaranteed () -> () + 28 (<compiler-generated>:0) 507 AppKit 0x0000000189c174a4 +[NSAppearance _performWithCurrentAppearance:usingBlock:] + 72 (NSAppearance.m:2408) 508 SwiftUI 0x00000001b53b2088 specialized static NSColor.withColorAppearance(in:_:) + 324 (AppKitColorConversions.swift:142) 509 SwiftUI 0x00000001b53b1e7c protocol witness for ColorProvider.resolve(in:) in conformance NSColor + 68 (<compiler-generated>:151) 510 SwiftUICore 0x0000000222436e6c ColorBox.resolve(in:) + 124 (Color.swift:288) full-log.crash
0
0
48
May ’25
DeviceActivityReport inside SwiftUI Button doesn’t receive tap gestures (ScreenTime API, iOS 17+)
Hi everyone, I’m experimenting with the new ScreenTime DeviceActivityReport view in SwiftUI (iOS 17 / Xcode 15). My goal is to show the report inside a Button (or, more generally, capture any tap on it) so that I can push a detail screen when the user selects it. Here’s the minimal code that reproduces the issue: import FamilyControls import DeviceActivity import SwiftUI struct ScreenTimeView: View { let center = AuthorizationCenter.shared @State private var context: DeviceActivityReport.Context = .init(rawValue: "Total Activity") @State private var filter = DeviceActivityFilter( segment: .hourly( during: Calendar.current.dateInterval(of: .day, for: .now)! ), users: .all, devices: .init([.iPhone, .iPad]) ) var body: some View { ZStack { DeviceActivityReport(context, filter: filter) } .onAppear { Task { do { try await center.requestAuthorization(for: .individual) } catch { print("Authorization failed:", error) } } } } } struct ContentView: View { var body: some View { ScrollViewReader { _ in ScrollView(showsIndicators: false) { VStack { Button { print("BUTTON TAPPED") // ← never fires } label: { ScreenTimeView() .frame(height: UIScreen.main.bounds.height * 1.4) } } } } } } ** What happens** DeviceActivityReport renders correctly with hourly bars. Tapping anywhere inside the Button does not trigger print("BUTTON TAPPED"). I’ve tried replacing Button with .onTapGesture, adding .contentShape(Rectangle()), and .allowsHitTesting(true), but nothing registers. What I’ve checked Authorisation succeeds—calling code in .onAppear prints no errors. Removing DeviceActivityReport and replacing it with a plain Rectangle() lets the tap gesture fire, so the issue seems specific to DeviceActivityReport.
0
0
74
May ’25
tvOS: Using .onExitCommand to Navigate to Home Tab Before Exiting — Is This Acceptable?
Hi Apple Developer Team, In my tvOS app built with SwiftUI, I have a tab-based interface with several sections. The first tab (index 0) is the Home tab. Other tabs include Contact, WiFi, Welcome, etc. I want to handle the remote's Menu / Back button (.onExitCommand) so that: If the user is on any tab other than Home (tabs 1, 2, 3, etc.), pressing the Menu button takes them back to the Home tab. If the user is already on the Home tab, then pressing the TV/Home button (not Menu) behaves as expected — suspending or exiting the app (handled by the system, no code involved). Here's a simplified version of what I implemented: .onExitCommand { if selectedTab != 0 { selectedTab = 0 focusedTab = 0 } else { // Let system handle the exit when user presses the TV/Home button } } This behavior ensures users don’t accidentally exit the app when they're browsing other tabs, and provides a consistent navigation experience. Question: Is this an acceptable and App Store-compliant use of .onExitCommand on tvOS? I'm not calling exit(0) or trying to force-terminate the app — just using .onExitCommand for in-app navigation purposes. Any official guidance or best practices would be greatly appreciated! Thanks, Prashant
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
36
May ’25
Enabling Show Tab Bar Programmatically
I have a macOS application developed in SwiftUI. It's a document-based application. I know how to hide the Show Tab Bar command under View. I don't want to hide it. I always want to show tabs. I wonder how to enable this command programmatically such that the document window always has the + button to the right. Thanks.
0
0
70
May ’25
Scroll offset incorrectly resets when animating insertion of ScrollView using .geometryGroup()
Hey, I've been having a problem with scroll views in combination with the .geometryGroup() modifier. I have filed a Feedback (FB17698293) but I also wanted to post this here in case someone maybe has a better workaround for the problem. Problem Whenever you conditionally insert a ScrollView inside a VStack that is modified with a .geometryGroup() modifier, the scroll view content offset resets itself after the insertion animation is done, even if you started scrolling inside the scroll view during the animation and haven't let go of the screen. This happens consistently and is fully reproducible (see below), both using a simulator and a real device. Unfortunately, this is a very annoying glitch that ruins a lot of cool UX components that rely on .geometryGroup(). The weird thing is that the glitch entirely disappears, if you add a simple, non-zero (but greater than 1) .padding() modifier to the VStack (.padding().geometryGroup()). I have no idea why this fixes the glitch, but it does. However, adding a padding is not feasible in many situations, so this workaround is not ideal. Steps to reproduce Launch the code below (using a simulator or a real device) and tap "Toggle Expansion" to insert the scroll view. As the view is animating in, drag the scroll content and hold it scrolled away from the top. Wait for the animation to complete. The scroll view will reset the content offset, even though the drag gesture is still active (i.e. you haven't lifted your finger to release the scroll view) On a real device, this sometimes even leads to an even worse visual artifact where the scroll view is rendered twice for a few frames; once with the correct offset, and once with the reset offset. I wanted to include a link to a gif/video showing the glitch, but it tells me that imgur is not allowed on the forums. Expected Behavior I want the scroll view to respect the content offset, even if I started changing it mid-animation. Xcode Version I am using Xcode 16.4 (16F6) but this problem has been occurring since the .geometryGroup() modifier has been release. I was only now able to pinpoint this problem exactly, so I'm filing this feedback. Code The entire code that reproduces the problem: import SwiftUI struct ContentView: View { @State private var isExpanded: Bool = false var body: some View { VStack { if isExpanded { ScrollView { Text(loremIpsum) } } Button("Toggle Expansion") { isExpanded.toggle() } } // .padding(10) // Adding a non-zero padding makes the glitch disappear .frame(maxWidth: .infinity) .geometryGroup() .animation(.default, value: isExpanded) } } #Preview { ContentView().preferredColorScheme(.dark) } // MARK: - Mock Data let loremIpsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt \ ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \ laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \ pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \ mollit anim id est laborum. """
Topic: UI Frameworks SubTopic: SwiftUI
0
0
52
May ’25
Mixing ReferenceFileDocument and @Observable
I have an app in which the data model is @Observable, and views see it through @Environment(dataModel.self) private var dataModel. Since there are a large number of views, only some of which may need to be redrawn at a given time, I believe that @Observable is more efficient at run time than @Published and @ObservedObject I’ve been trying to make the app document based. Although I started using SwiftData, it has trouble with Codable, and a long thread in the Developer forum suggests that SwiftData does not support the Undo manager - and in any event, simple JSON serialization is all that this app requires. Unfortunately, ReferenceFileDocument inherits from ObservableObject, which seems to not play nice with @Observable. I’d like to keep using @Observable, but haven’t been able to figure out how. When I deserialize a JSON ReferenceFileDocument, I can’t seem to connect it to an @Observable class instance and to let the various views and view models know where to find and update it. I’d appreciate advice on how to implement document persistence in this app. Also, the default behaviour of DoumentGroup provides a nice menu to, another things, rename a new file to something other than Untitled xx, but it doesn’t appear to work (there is an extensive thread on the Developer website discussing this issue). Is there a solution to this problem? Thanks for any help you can offer.
3
0
87
May ’25
Updating sort order of items in a LazyVGrid
I have a grid setup where I'm displaying multiple images which is working fine. Images are ordered by the date they're added, newest to oldest. I'm trying to set it up so that the user can change the sort order themselves but am having trouble getting the view to update. I'm setting the fetch request using oldest to newest as default when initialising the view, then when its appears updating the sort descriptor struct ProjectImagesListView: View { @Environment(\.managedObjectContext) private var viewContext var project : Project let columns = [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ] @FetchRequest var pictures: FetchedResults<Picture> var body: some View { ScrollView { LazyVGrid(columns: columns) { ForEach(pictures) { picture in NavigationLink(destination: ProjectImageDetailView(picture: picture)) { if let pictureData = picture.pictureThumbnailData, let uiImage = UIImage(data: pictureData) { Image(uiImage: uiImage) .resizable() .scaledToFit() .frame(height: 100) } else { Image("missing") .resizable() .scaledToFit() .frame(height: 100) } } } } } .navigationBarTitle("\(project.name ?? "") Images", displayMode: .inline) .onAppear() { guard let sortOrder = getSettingForPhotoOrder() else { return } guard let sortOrderValue = sortOrder.settingValue else { return } NSLog("sortOrderPhotos: \(String(describing: sortOrder.settingValue))") if sortOrderValue == "Newest" { NSLog("sortOrderPhotos: Change from default") let newSortDescriptor = NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: false) pictures.nsSortDescriptors = [newSortDescriptor] } } } func getSettingForPhotoOrder() -> Setting? { let fetchRequest: NSFetchRequest<Setting> = Setting.fetchRequest() fetchRequest.predicate = NSPredicate(format: "name = %@", "photoSortOrder") fetchRequest.fetchLimit = 1 do { let results = try viewContext.fetch(fetchRequest) return results.first } catch { print("Fetching Failed") } return nil } init(project: Project) { self.project = project _pictures = FetchRequest( entity: Picture.entity(), sortDescriptors: [ NSSortDescriptor(keyPath: \Picture.dateTaken, ascending: true) ], predicate: NSPredicate(format: "project == %@", project) ) } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
61
May ’25
How to achieve a pure backdrop blur effect without predefined tint color in SwiftUI / UIKit?
Hi everyone, I’m currently trying to create a pure backdrop blur effect in my iOS app (SwiftUI / UIKit), similar to the backdrop-filter: blur(20px) effect in CSS. My goal is simple: • Apply a Gaussian blur (radius ~20px) to the background content • Overlay a semi-transparent black layer (opacity 0.3) • Avoid any predefined color tint from UIBlurEffect or .ultraThinMaterial, etc. However, every method I’ve tried so far (e.g., .ultraThinMaterial, UIBlurEffect(style:)) always introduces a built-in tint, which makes the result look gray or washed out. Even when layering a black color with opacity 0.3 over .ultraThinMaterial, it doesn’t give the clean, transparent-black + blur look I want. What I’m looking for: • A clean 20px blur effect (like CIGaussianBlur) • No color shift/tint added by default • A layer of black at 30% opacity on top of the blur • Ideally works live (not a static snapshot blur) Has anyone achieved something like this in UIKit or SwiftUI? Would really appreciate any insights, workarounds, or libraries that can help. Thanks in advance! Ben
3
0
87
May ’25
visionOS NavigationSplitView - Refreshable ProgressView Disappears
Description I've encountered an issue with NavigationSplitView on visionOS when using a refreshable ScrollView or List in the detail view. The Problem: When implementing pull-to-refresh in the detail view of a NavigationSplitView, the ProgressView disappears and generates this warning: Trying to convert coordinates between views that are in different UIWindows, which isn't supported. Use convertPoint:fromCoordinateSpace: instead. I discovered that if the detail view includes a .navigationTitle(), the ProgressView remains visible and works correctly! Below is a minimal reproducible example showing this behavior. When you run this code, you'll notice: The sidebar refreshable works fine The detail refreshable works only when .navigationTitle("Something") is present Remove the navigationTitle and the detail view's refresh indicator disappears minimal Demo import SwiftUI struct MinimalRefreshableDemo: View { @State private var items = ["Item 1", "Item 2", "Item 3"] @State private var detailItems = ["Detail 1", "Detail 2", "Detail 3"] @State private var selectedItem: String? = "Item 1" var body: some View { NavigationSplitView { List(items, id: \.self, selection: $selectedItem) { item in Text(item) } .refreshable { items = ["Item 1", "Item 2", "Item 3"] } .navigationTitle("Chat") } detail: { List { ForEach(detailItems, id: \.self) { item in Text(item) .frame(height: 100) .frame(maxWidth: .infinity) } } .refreshable { detailItems = ["Detail 1", "Detail 2", "Detail 3"] } .navigationTitle("Something") } } } #Preview { MinimalRefreshableDemo() } Is this expected behavior? Has anyone else encountered this issue or found a solution that doesn't require adding a navigation title?
1
0
50
May ’25
SwiftUI List - onInsert not called on iOS (works on macOS)
I am working with a simple SwiftUI List and I want to enable functionality that allows files and images to be dropped onto the List from outside the app. There is an onInsert modifier with List that allows for this, but I found that it works on macOS, but not when running the same view on iOS. I have sample code that I can't seem to post on this forum because it keeps giving me a validation error about "This post contains sensitive language". Maybe this will work: Code to reproduce issue Is there anything I can do to make this work on iOS?
1
0
62
May ’25
UI not updating during render
I've coded a small raytracer that renders a scene (based on Peter Shirley's tutorial, I just coded it in Swift). The raytracer itself works fine, outputs a PPM file which is correct. However, I was hoping to enclose this in a UI that will update the picture as each pixel value gets updated during the render. So to that end I made a MacOS app, with a basic model-view architecture. Here is my model: // // RGBViewModel.swift // rtweekend_gui // // import SwiftUI // RGB structure to hold color values struct RGB { var r: UInt8 var g: UInt8 var b: UInt8 } // ViewModel to handle the RGB array and updates class RGBViewModel: ObservableObject { // Define the dimensions of your 2D array let width = 1200 let height = 675 // Published property to trigger UI updates @Published var rgbArray: [[RGB]] init() { // Initialize with black pixels rgbArray = Array(repeating: Array(repeating: RGB(r: 0, g: 0, b: 0), count: width), count: height) } func render_scene() { for j in 0..&lt;height { for i in 0..&lt;width { // Generate a random color let r = UInt8.random(in: 0...255) let g = UInt8.random(in: 0...255) let b = UInt8.random(in: 0...255) // Update on the main thread since this affects the UI DispatchQueue.main.async { // Update the array self.rgbArray[j][i] = RGB(r: r, g: g, b: b) } } } } and here is my view: // // RGBArrayView.swift // rtweekend_gui // // import SwiftUI struct RGBArrayView: View { // The 2D array of RGB values @StateObject private var viewModel = RGBViewModel() // Control the size of each pixel private let pixelSize: CGFloat = 1 var body: some View { VStack { // Display the RGB array Canvas { context, size in for y in 0..&lt;viewModel.rgbArray.count { for x in 0..&lt;viewModel.rgbArray[y].count { let rgb = viewModel.rgbArray[y][x] let rect = CGRect( x: CGFloat(x) * pixelSize, y: CGFloat(y) * pixelSize, width: pixelSize, height: pixelSize ) context.fill( Path(rect), with: .color(Color( red: Double(rgb.r) / 255.0, green: Double(rgb.g) / 255.0, blue: Double(rgb.b) / 255.0 )) ) } } } .border(Color.gray) // Button to start filling the array Button("Render") { viewModel.render_scene() } .padding() } .padding() .frame(width: CGFloat(viewModel.width) * pixelSize + 40, height: CGFloat(viewModel.height) * pixelSize + 80) } } // Preview for SwiftUI struct RGBArrayView_Previews: PreviewProvider { static var previews: some View { RGBArrayView() } } The render does work and the image displays, however, I thought I set it up to show the image updating pixel by pixel and that doesn't happen, the image shows up all at once. What am I doing wrong?
0
0
44
May ’25
FamilyActivityTitleView Label has wrong text color when app is using different than system theme
Hello, In a new app I am working on I noticed the FamilyActivityTitleView that displays "ApplicationToken" has wrong (black) color when phone is set to light mode but app is using dark mode via override. We display user's selected apps and the labels are rendered correctly at first, but then when user updates selection with FamilyActivityPicker, then those newly added apps are rendered with black titles. The problem goes away when I close the screen and open it again. It also doesn't happen when phone is set to dark theme. I am currently noticing the issue on iOS 18.4.1. I have tried various workarounds like forcing white text in the custom label style, forcing re-render with custom .id value but nothing helped. Is there any way how to fix this?
0
0
46
May ’25