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

A Summary of the WWDC25 Group Lab - SwiftUI
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for SwiftUI. What's your favorite new feature introduced to SwiftUI this year? The new rich text editor, a collaborative effort across multiple Apple teams. The safe area bar, simplifying the management of scroll view insets, safe areas, and overlays. NavigationLink indicator visibility control, a highly requested feature now available and back-deployed. Performance improvements to existing components (lists, scroll views, etc.) that come "for free" without requiring API adoption. Regarding performance profiling, it's recommended to use the new SwiftUI Instruments tool when you have a good understanding of your code and notice a performance drop after a specific change. This helps build a mental map between your code and the profiler's output. The "cause-and-effect graph" in the tool is particularly useful for identifying what's triggering expensive view updates, even if the issue isn't immediately apparent in your own code. My app is primarily UIKit-based, but I'm interested in adopting some newer SwiftUI-only scene types like MenuBarExtra or using SwiftUI-exclusive features. Is there a better way to bridge these worlds now? Yes, "scene bridging" makes it possible to use SwiftUI scenes from UIKit or AppKit lifecycle apps. This allows you to display purely SwiftUI scenes from your existing UIKit/AppKit code. Furthermore, you can use SwiftUI scene-specific modifiers to affect those scenes. Scene bridging is a great way to introduce SwiftUI into your apps. This also allows UIKit apps brought to Vision OS to integrate volumes and immersive spaces. It's also a great way to customize your experience with Assistive Access API. Can you please share any bad practices we should avoid when integrating Liquid Glass in our SwiftUI Apps? Avoid these common mistakes when integrating liquid glass: Overlapping Glass: Don't overlap liquid glass elements, as this can create visual artifacts. Scrolling Content Collisions: Be cautious when using liquid glass within scrolling content to prevent collisions with toolbar and navigation bar glass. Unnecessary Tinting: Resist the urge to tint the glass for branding or other purposes. Liquid glass should primarily be used to draw attention and convey meaning. Improper Grouping: Use the GlassEffectContainer to group related glass elements. This helps the system optimize rendering by limiting the search area for glass interactions. Navigation Bar Tinting: Avoid tinting navigation bars for branding, as this conflicts with the liquid glass effect. Instead, move branding colors into the content of the scroll view. This allows the color to be visible behind the glass at the top of the view, but it moves out of the way as the user scrolls, allowing the controls to revert to their standard monochrome style for better readability. Thanks for improving the performance of SwiftUI List this year. How about LazyVStack in ScrollView? Does it now also reuse the views inside the stack? Are there any best practices for improving the performance when using LazyVStack with large number of items? SwiftUI has improved scroll performance, including idle prefetching. When using LazyVStack with a large number of items, ensure your ForEach returns a static number of views. If you're returning multiple views within the ForEach, wrap them in a VStack to signal to SwiftUI that it's a single row, allowing for optimizations. Reuse is handled as an implementation detail within SwiftUI. Use the performance instrument to identify expensive views and determine how to optimize your app. If you encounter performance issues or hitches in scrolling, use the new SwiftUI Instruments tool to diagnose the problem. Implementing the new iOS 26 tab bar seems to have very low contrast when darker content is underneath, is there anything we should be doing to increase the contrast for tab bars? The new design is still in beta. If you're experiencing low contrast issues, especially with darker content underneath, please file feedback. It's generally not recommended to modify standard system components. As all apps on the platform are adopting liquid glass, feedback is crucial for tuning the experience based on a wider range of apps. Early feedback, especially regarding contrast and accessibility, is valuable for improving the system for all users. If I’m starting a new multi-platform app (iOS/iPadOS/macOS) that will heavily depend on UIKit/AppKit for the core structure and components (split, collection, table, and outline views), should I still use SwiftUI to manage the app lifecycle? Why? Even if your new multi-platform app heavily relies on UIKit/AppKit for core structure and components, it's generally recommended to still use SwiftUI to manage the app lifecycle. This sets you up for easier integration of SwiftUI components in the future and allows you to quickly adopt new SwiftUI features. Interoperability between SwiftUI and UIKit/AppKit is a core principle, with APIs to facilitate going back and forth between the two frameworks. Scene bridging allows you to bring existing SwiftUI scenes into apps that use a UIKit lifecycle, or vice versa. Think of it not as a binary choice, but as a mix of whatever you need. I’d love to know more about the matchedTransitionSource API you’ve added - is it a native way to have elements morph from a VStack to a sheet for example? What is the use case for it? The matchedTransitionSource API helps connect different views during transitions, such as when presenting popovers or other presentations from toolbar items. It's a way to link the user interaction to the presented content. For example, it can be used to visually connect an element in a VStack to a sheet. It can also be used to create a zoom effect where an element appears to enlarge, and these transitions are fully interactive, allowing users to swipe. It creates a nice, polished experience for the user. Support for this API has been added to toolbar items this year, and it was already available for standard views.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
1.3k
Jun ’25
IOS Swift touch screen issue
MyOwnKeyboard Pad app has 4 text views with textfields that use touch screen for editing. There is one view, Compose, that has a textfield and a textview (UIRepresentable). The app enters text into the view using textfield buttons. The app has total control of editing. When entering text if the screen is touched it conflicts the cursor position and creates an "out of bounds" failure. In that view the app does not need any touch events. I need a method in UIRepresentable to disable the touch event. I am not familiar with UIRepresentable as this code was provided by Apple to solve a 16 bit unicode character issue. What would be the code to disable touch events in the UIRepresentable compose view. The app is free for a while until this problem is fixed. It is for iPads 11"+ . The name in the app store is MyOwnKeyboard Pad. I know some great engineer will find the answer. DTS tried. Thanks to all, maybe I'll sell some. Charlie 25mar26
1
0
103
12h
ScrollView clipping nav title in iOS 26?
When using a ScrollView inside some sort of navigation (stack or split view), large navigation titles seem to get clipped to the width of the scroll content for some reason? Minimal example: struct ContentView: View { var body: some View { NavigationStack { ScrollView { Text("Scroll Content") } .navigationTitle("Navigation Title") } } } Results in: Is this a bug in the beta, or has something changed and now I’m doing things wrong?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
3
0
241
21h
Localization in Swift macOS console Apps.
Is it possible to build localization into console apps, developed in SwiftUI in Xcode26. I have created a catalog, (.xcstrings file) with an English and fr-CA string. I have tried to display the French text without success. I am using the console app to test a package which also has English/French text. English text works fine in both package and the console main, but I cannot generate the French. From what I can discover so far it's not possible without bundling it as a .app, (console app). Looking for anyone who has crossed this bridge.
7
0
259
1d
SwiftUI Chart scrolling on macOS
I'm running macOS 26.3 and using Xcode 26.4. I'm trying to create a SwiftUI Chart that can scroll horizontally. In the SwiftUI Preview, and also running the app on macOS, the chart displays a scrollbar, but the scrollbar does not respond to mouse interaction (dragging the scrollbar, or clicking in the gutters on either side of the scrollbar). Here's the sample code: import SwiftUI import Charts private struct DataPoint: Identifiable { let id: Int let x: Double let value: Double } struct ContentView: View { private let points: [DataPoint] = (0..<60).map { index in let wave = sin(Double(index) * 0.28) * 18 let trend = Double(index) * 0.35 return DataPoint(id: index, x: Double(index), value: 60 + wave + trend) } var body: some View { Chart(points) { point in BarMark( x: .value("Data Point", point.x), y: .value("Value", point.value) ) .foregroundStyle(.blue.gradient) } .chartScrollableAxes(.horizontal) // Doesn't work: // .scrollIndicators(.hidden) // .never also does not work .chartXVisibleDomain(length: 20) .padding() } } #Preview { ContentView() }
3
0
100
1d
NavigationLink selection in DisclosureGroup not working with .draggable modifier
NavigationLink selection in DisclosureGroup not working with .draggable modifier This was recently also posted here: https://stackoverflow.com/questions/79914290/ I am playing around with a tree data structure with folders and entries.I would like to add dragging of entries and folders between folders, using .draggable and dropDestination. In my current code, dragging works, but selection of entries no longer works, except if I click outside of the Text If I comment out .draggable(subfolder.name) in func FolderRow(), selection works as expected. How can I make sure both selection and drag and drop works for both folders and entries? I also tried using Transferable and Codable, but I get the same result. Here is an MRE: import SwiftData import SwiftUI @Model final class Folder { @Attribute(.unique) var name: String // Parent var parentFolder: Folder? // Child folders @Relationship(deleteRule: .cascade, inverse: \Folder.parentFolder) var subfolders: [Folder] = [] // Leaf entries @Relationship(deleteRule: .cascade, inverse: \Entry.folder) var entries: [Entry] = [] init(name: String, parentFolder: Folder? = nil) { self.name = name self.parentFolder = parentFolder } } @Model final class Entry { @Attribute(.unique) var name: String var detail: String var folder: Folder? // recursive relationship init(name: String, detail: String) { self.name = name self.detail = detail } } @main struct TestMacApp: App { var body: some Scene { WindowGroup { SidebarView() .modelContainer(for: Folder.self) } } } struct SidebarView: View { @Environment(\.modelContext) private var context @Query(filter: #Predicate<Folder> { $0.parentFolder == nil }) private var rootFolders: [Folder] var body: some View { NavigationSplitView { List { ForEach(rootFolders) { folder in FolderRow(folder: folder) .draggable(folder.name) } } } detail: { Text("detail") } .onAppear { seed() } } } struct FolderRow: View { @Environment(\.modelContext) private var context var folder: Folder @State private var isExpanded: Bool = true var body: some View { DisclosureGroup(isExpanded: $isExpanded) { // Subfolders ForEach(folder.subfolders) { subfolder in FolderRow(folder: subfolder) .draggable(subfolder.name) // disabling this line fixes the selection } // Entries (leaf nodes) ForEach(folder.entries) { entry in NavigationLink(destination: EntryDetail(entry: entry)) { EntryRow(entry: entry) } .draggable(entry.name) } } label: { Label(folder.name, systemImage: "folder") } .dropDestination(for: String.self) { names, _ in return handleDrop(of: names) } } } struct EntryRow: View { var entry: Entry var body: some View { Text(entry.name) } } struct EntryDetail: View { var entry: Entry var body: some View { Text(entry.detail) } } extension FolderRow { private func handleDrop(of names: [String]) -> Bool { do { for name in names { if let droppedEntry = try context.fetchFilteredModel(filter: #Predicate<Entry> { x in x.name == name }) { droppedEntry.folder = folder print("dropped \(droppedEntry.name) on \(folder.name)") } else if let droppedFolder = try context.fetchFilteredModel(filter: #Predicate<Folder> { x in x.name == name }) { if droppedFolder.parentFolder != nil && droppedFolder != folder { droppedFolder.parentFolder = folder print("dropped \(droppedFolder.name) on \(folder.name)") } } } return true } catch { debugPrint(error.localizedDescription) return false } } } extension SidebarView { private func seed() { do { // delete current models for folder: Folder in try context.fetchAllModels() { context.delete(folder) } try context.save() let rootFolder = Folder(name: "Root") let entry1 = Entry(name: "One", detail: "Detail One") let entry2 = Entry(name: "Two", detail: "Detail Two") rootFolder.entries.append(contentsOf: [entry1, entry2]) let subFolder1 = Folder(name: "Sub1", parentFolder: rootFolder) let entry3 = Entry(name: "Three", detail: "Detail Three") let entry4 = Entry(name: "Four", detail: "Detail Four") subFolder1.entries.append(contentsOf: [entry3, entry4]) let subFolder2 = Folder(name: "Sub2", parentFolder: rootFolder) let entry5 = Entry(name: "Five", detail: "Detail Five") let entry6 = Entry(name: "Six", detail: "Detail Six") subFolder2.entries.append(contentsOf: [entry5, entry6]) context.insert(rootFolder) } catch { debugPrint(error) } } } extension ModelContext { // convenience methods func fetchAllModels<M>() throws -> [M] where M: PersistentModel { let fetchDescriptor = FetchDescriptor<M>() return try fetch(fetchDescriptor) } func fetchFilteredModels<M>(filter: Predicate<M>) throws -> [M] where M: PersistentModel { let fetchDescriptor = FetchDescriptor<M>(predicate: filter) return try fetch(fetchDescriptor) } func fetchFilteredModel<M>(filter: Predicate<M>) throws -> M? where M: PersistentModel { return try fetchFilteredModels(filter: filter).first } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
161
1d
Combining NavigationSplitView and TabView in iOS 18
Hi folks, I've used a NavigationSplitView within one of the tabs of my app since iOS 16, but with the new styling in iOS 18 the toolbar region looks odd. In other tabs using e.g. simple stacks, the toolbar buttons are horizontally in line with the new tab picker, but with NavigationSplitView, the toolbar leaves a lot of empty space at the top (see below). Is there anything I can do to adjust this, or alternatively, continue to use the old style? Thanks!
13
3
2.9k
1d
On macOS Settings window navigation bar item is in the center
Hi, Overview I have a Mac app with a settings window. When I add a button it is added to the center. I want it on the trailing edge, I even tried adding it as confirmationAction but doesn’t work. Screenshot Feedback FB21374186 Steps to reproduce Run the project on mac Open the app's settings by pressing ⌘ , Notice that the Save button is in the center instead of the trailing edge Code App import SwiftUI @main struct SettingsToolbarButtonBugApp: App { var body: some Scene { WindowGroup { ContentView() } Settings { SettingsView() .frame(width: 300, height: 400) } } } SettingsView import SwiftUI struct SettingsView: View { var body: some View { NavigationStack { Form { Text("Settings window") } .toolbar { ToolbarItem(placement: .confirmationAction) { // Save button is the center instead of trailing edge Button("Save") {} } } .navigationTitle("Settings") } } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
173
2d
MapKit in SwiftUI
Anyone worked with MapKit's MapCameraPosition in SwiftUI? I'm building a navigation app and ran into a limitation I can't find a clean solution for when using .userLocation(followsHeading: true) MapKit takes full control of the camera, smooth heading tracking, follows the user automatically. Perfect. But there's no way to set a custom pitch (tilt) on it. The only initializer available is... .userLocation(followsHeading: true, fallback: .automatic) No pitch, no distance parameters.... The workaround I found is setting .camera(MapCamera(..., pitch: 60)) first, waiting 200ms, then switching to .userLocation(followsHeading: true), MapKit inherits the pitch from the rendered camera state before handing off to user tracking.... It works, but it's clearly exploiting an undocumented behaviour in MapKit's state machine rather than a proper API Has anyone found a cleaner way to achieve this? Or is UIViewRepresentable wrapping MKMapView the only proper solution? It would be awesome to have something like this cameraPosition = .userLocation( followsHeading: true, pitch: 60, distance: 800, fallback: .automatic )
1
0
114
2d
How to recreate Apple Music mini player transition in SwiftUI
Hello, I am building an audio player app in SwiftUI and trying to recreate the behavior of Apple Music's mini player and full player. I'm struggling to get the animation to seamlessly transition between the mini player and the full player. Currently, it feels disconnected and doesn't resemble the smooth animation seen in Apple Music. What I want to achieve: Full player that expands/collapses from/to the mini player Smooth artwork transition between both states Drag down to collapse the full player Support both newer APIs like tabViewBottomAccessory and older iOS versions Questions: What is the best way to build this transition in SwiftUI? Should I use matchedGeometryEffect or something else? Should this be a custom container instead of fullScreenCover? How would you support both new and older iOS versions? What is the best way to implement drag to dismiss? Thanks for any help! Example code: struct ContentView: View { @State private var isFullPlayerPresented = false var body: some View { TabView { Tab("Home", systemImage: "house") { Text("Home") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.green) } Tab("Library", systemImage: "rectangle.stack.fill") { Text("Library") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.brown) } } .tabViewBottomAccessory(isEnabled: !isFullPlayerPresented) { MiniPlayerView(isFullPlayerPresented: $isFullPlayerPresented) } .fullScreenCover(isPresented: $isFullPlayerPresented) { // Maybe it's not a full screen cover presentation in Apple Music? FullPlayerView(isFullPlayerPresented: $isFullPlayerPresented) } } } Mini player: struct MiniPlayerView: View { @Binding var isFullPlayerPresented: Bool var body: some View { Button { isFullPlayerPresented = true } label: { HStack { Image(systemName: "photo") .resizable() .scaledToFit() .frame(width: 30, height: 30) .clipShape(.rect(cornerRadius: 8)) Spacer() Text("Tap to open full player") Spacer() Button("", systemImage: "play.fill", action: {}) } .padding(.horizontal) .padding(.vertical, 4) } .foregroundStyle(.white) } } Full player: struct FullPlayerView: View { @Binding var isFullPlayerPresented: Bool var body: some View { // This art work needs to snaps to the artwork in mini player Image(systemName: "photo") .resizable() .scaledToFit() .frame(width: 250, height: 250) .clipShape(.rect(cornerRadius: 20)) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.red) .overlay(alignment: .topTrailing) { Button(role: .close) { isFullPlayerPresented = false } .foregroundStyle(.white) .padding() } } }
0
0
119
3d
Wrong position of searchable component on first render
Hey all, I found a weird behaviour with the searchable component. I created a custom bottom nav bar (because I have custom design in my app) to switch between screens. On one screen I display a List component with the searchable component. Whenever I enter the search screen the first time, the searchable component is displayed at the bottom. This is wrong. It should be displayed at the top under the navigationTitle. When I enter the screen a second time, everything is correct. This behaviour can be reproduced on all iOS 26 versions on the simulator and on a physical device with debug and release build. On iOS 18 everything works fine. Steps to reproduce: Cold start of the app Click on Search TabBarIcon (searchable wrong location) Click on Home TabBarIcon Click on Search TabBarIcon (searchable correct location) Simple code example: import SwiftUI struct ContentView: View { @State var selectedTab: Page = Page.main var body: some View { NavigationStack { ZStack { VStack { switch selectedTab { case .main: MainView() case .search: SearchView() } } VStack { Spacer() VStack(spacing: 0) { HStack(spacing: 0) { TabBarIcon(iconName: "house", selected: selectedTab == .main, displayName: "Home") .onTapGesture { selectedTab = .main } TabBarIcon(iconName: "magnifyingglass", selected: selectedTab == .search, displayName: "Search") .onTapGesture { selectedTab = .search } } .frame(maxWidth: .infinity) .frame(height: 55) .background(Color.gray) } .ignoresSafeArea(.all, edges: .bottom) } } } } } struct TabBarIcon: View { let iconName: String let selected: Bool let displayName: String var body: some View { ZStack { VStack { Image(systemName: iconName) .resizable() .renderingMode(.template) .aspectRatio(contentMode: .fit) .foregroundColor(Color.black) .frame(width: 22, height: 22) Text(displayName) .font(Font.system(size: 10)) } } .frame(maxWidth: .infinity) } } enum Page { case main case search } struct MainView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .navigationTitle("Home") } } struct SearchView: View { @State private var searchText = "" let items = [ "Apple", "Banana", "Pear", "Strawberry", "Orange", "Peach", "Grape", "Mango" ] var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.localizedCaseInsensitiveContains(searchText) } } } var body: some View { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") } }
4
0
243
3d
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
0
0
31
4d
onDisappear not called when closing a document on macOS (Designed for iPad), works on iPad
When running a SwiftUI DocumentGroup app on macOS designed for iPad, onDisappear is not called when closing a document, and deinit of state objects owned by a ContentView is not invoked. This behavior works as expected on iPad. @main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyDocument()) { file in ContentView(document: file.$document) .onDisappear { print("This isn't called on macOS Designed For iPad, but is on iPad when closing a document.") } } } } It is my understanding that for a macOS designed for iPad these lifecycle events would behave the same - otherwise there appears to be no way to detect if a document has closed on macOS.
1
0
64
4d
iPadOS 26 Crash when num pad with floating keyboard in presented view
Build the sample code below, type something in the textfield (make sure the num pad is a popup and that the text keyboard is floating). And tap multiple times outside of the textfield in the sheet. That will lead to the crash: *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x60000179cec0 "UIView:0x103c52fe0.top"> and <NSLayoutYAxisAnchor:0x6000017e0800 "_UIRemoteKeyboardPlaceholderView:0x103baa240.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.' terminating due to uncaught exception of type NSException CoreSimulator 1051.17.8 - Device: iPad Pro 13-inch (M5) (655000D7-41BC-4B13-BD07-BBA80D892E97) - Runtime: iOS 26.2 (23C54) - DeviceType: iPad Pro 13-inch (M5) Does anyone have the slightest idea of a workaround? I can't find one. import SwiftUI struct ContentView: View { var body: some View { Text("Content") .sheet(isPresented: .constant(true)) { PresentedView() } } } struct PresentedView: View { @State private var text = "" var body: some View { ScrollView { VStack { TextField("Placeholder", text: $text) .keyboardType(.numberPad) } .padding(80) } } } See here for discussion and video to reproduce: https://stackoverflow.com/questions/79905933/ipados-26-crash-when-floating-num-pad-in-presented-view
0
1
14
5d
Unwanted animation of navbar controls
What could cause the issue shown on the gif. At first I though clean build folder helps. But when you close the main window and open it after some time it gets back to this state. The whole set of elements in the navbar starts shifting to the right and it continues infinitely 15.6.1 (24G90) Swift 6.1.2
2
0
66
5d
Zoom navigation transitions for tabViewBottomAccessory are not working in SwiftUI with ObservableObject or Observable
The zoom navigation transition with matchedTransitionSource in tabViewBottomAccessory does not work when a Published var in an ObservableObjector Observable gets changed. Here is an minimal reproducible example with ObservableObject: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace @StateObject private var viewModel = ViewModel() // @State private var isPresented = false var body: some View { TabView { Button { viewModel.isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $viewModel.isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { viewModel.isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } } However, when using only a State property everything works: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace // @StateObject private var viewModel = ViewModel() @State private var isPresented = false var body: some View { TabView { Button { isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } }
7
1
383
5d
Bottom toolbar Button truncated on Mac Catalyst 26
On Mac Catalyst 26, a Button bar item in a bottom toolbar look squished. This happens only when the "Mac Catalyst Interface" option is set to "Optimize for Mac". When it is set to "Scale to match iPad", the buttons look fine. For example, in the screenshots below, the text button should say "Press Me", instead of "…" A simple reproducible snippet and a screenshot below. The toolbar button comparison between "Scale to match iPad" and "Optimize for Mac" are shown. Optimize for Mac Scale to match iPad import SwiftUI struct ContentView: View { @State private var selectedItem: String? = "Item 1" let items = ["Item 1", "Item 2"] var body: some View { NavigationSplitView { List(items, id: \.self, selection: $selectedItem) { item in Text(item) } .navigationTitle("Items") } detail: { if let selectedItem = selectedItem { Text("Detail view for \(selectedItem)") .toolbar { ToolbarItemGroup(placement: .bottomBar) { Text("Hello world") Spacer() Button("Press Me") { } Spacer() Button { } label: { Image(systemName: "plus") .imageScale(.large) } } } } else { Text("Select an item") } } } }
3
2
439
5d
Charts performance issue
Hi, I want to recreate a chart from Apple Health and I have code like this. When I scroll - especially the week and month charts, there are performance issues. If I remove .chartScrollPosition(x: $scrollChartPosition), it runs smoothly, but I need to know which part of the chart is currently displayed. Can you help me? import Charts import SwiftUI struct MacroChartView: View { var selectedRange: ChartRange var binnedPoints: [MacroBinPoint] @State private var scrollChartPosition: Date = .now var body: some View { VStack { Text("\(selectedRange.rangeLabel(for: scrollChartPosition))") Chart(binnedPoints) { point in BarMark( x: .value("Date", point.date, unit: selectedRange.binComponent), y: .value("Calories", point.calories) ) } .frame(height: 324) .chartXVisibleDomain(length: selectedRange.visibleDomainLength()) .chartScrollableAxes(.horizontal) .chartScrollPosition(x: $scrollChartPosition) .chartScrollTargetBehavior(.valueAligned(matching: selectedRange.scrollAlignmentComponents)) .chartXAxis { switch selectedRange { case .week: AxisMarks(values: .stride(by: .day)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.weekday(.abbreviated)) } case .month: AxisMarks(values: .stride(by: .weekOfYear)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.day()) } case .halfYear: AxisMarks(values: .stride(by: .month)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.month(.abbreviated)) } case .year: AxisMarks(values: .stride(by: .month)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.month(.abbreviated)) } } } } } } enum MeasurementHistoryMode { case macros case comparisons } enum MacroKindToDisplay { case protein, fat, carbs } enum MacrosDisplayMode: Equatable { case all case single(MacroKindToDisplay) } enum ChartRange: String, CaseIterable { case week = "T" case month = "M" case halfYear = "6M" case year = "R" var binComponent: Calendar.Component { switch self { case .week, .month: return .day case .halfYear: return .weekOfYear case .year: return .month } } var scrollAlignmentComponents: DateComponents { switch self { case .week: return DateComponents(hour: 0, minute: 0, second: 0) case .month: return DateComponents(hour: 0) case .halfYear: return DateComponents(weekday: 1) case .year: return DateComponents(day: 1) } } func visibleDomainLength() -> Int { switch self { case .week: return 7 * 24 * 60 * 60 case .month: return 31 * 24 * 60 * 60 case .halfYear: return 6 * 31 * 24 * 60 * 60 case .year: return 12 * 31 * 24 * 60 * 60 } } func start(for date: Date) -> Date { let cal = Calendar.current switch self { case .week, .month: return cal.startOfDay(for: date) case .halfYear: return cal.dateInterval(of: .weekOfYear, for: date)?.start ?? cal.startOfDay(for: date) case .year: return cal.dateInterval(of: .month, for: date)?.start ?? cal.startOfDay(for: date) } } func rangeLabel(for start: Date) -> String { let end = start.addingTimeInterval(TimeInterval(visibleDomainLength())) let f = DateFormatter() f.dateFormat = Calendar.current.isDate(start, inSameDayAs: end) ? "MMM d" : "MMM d" return Calendar.current.isDate(start, inSameDayAs: end) ? f.string(from: start) : "\(f.string(from: start)) – \(f.string(from: end))" } } struct MacrosPoint: Identifiable { var id: Date { date } let date: Date let calories: Double let proteinInGrams: Double let carbsInGrams: Double let fatInGrams: Double } struct MacroBinPoint: Identifiable { var id: Date { date } let date: Date let calories: Double let proteinKcal: Double let carbsKcal: Double let fatKcal: Double } func bin(points: [MacrosPoint], for period: ChartRange) -> [MacroBinPoint] { let grouped = Dictionary(grouping: points) { point in period.start(for: point.date) } let bins = grouped.map { (start, items) -> MacroBinPoint in var calories = items.reduce(0) { $0 + $1.calories } var proteinKcal = items.reduce(0) { $0 + $1.proteinInGrams * 4 } var carbsKcal = items.reduce(0) { $0 + $1.carbsInGrams * 4 } var fatKcal = items.reduce(0) { $0 + $1.fatInGrams * 9 } calories /= Double(items.count) proteinKcal /= Double(items.count) carbsKcal /= Double(items.count) fatKcal /= Double(items.count) return MacroBinPoint(date: start, calories: calories, proteinKcal: proteinKcal, carbsKcal: carbsKcal, fatKcal: fatKcal) } .sorted { $0.date < $1.date } return bins } struct ExampleData { static let macrosPoints: [MacrosPoint] = [ MacrosPoint(date: Date(timeIntervalSince1970: 1687949774), calories: 1895, proteinInGrams: 115, carbsInGrams: 192, fatInGrams: 72),... ]
0
0
104
1w
iOS 26: Toolbar button background flashes black during NavigationStack transitions (dark mode)
I’m seeing a visual glitch with toolbar buttons when building with Xcode 26 for iOS 26. During transitions (both pushing in a NavigationStack and presenting a .sheet with its own NavigationStack), the toolbar button briefly flashes the wrong background colour (black in dark mode, white in light mode) before animating to the correct Liquid Glass appearance. This happens even in a minimal example and only seems to affect system toolbar buttons. A custom view with .glassEffect() doesn’t have the issue. I’ve tried: .tint(...), UINavigationBarAppearance/UIToolbarAppearance, and setting backgrounds on hosting/nav/window but none of those made any difference. Here’s a minimal reproducible example: import SwiftUI struct ContentView: View { @State private var showingSheet = false var body: some View { NavigationStack { List { NavigationLink("Push (same stack — morphs)") { DetailView() } Button("Sheet (separate stack — flashes)") { showingSheet = true } } .navigationTitle("Root") .scrollContentBackground(.hidden) .background(.gray) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } .sheet(isPresented: $showingSheet) { SheetView() } } } } struct DetailView: View { var body: some View { Text("Detail (same stack)") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.gray) .navigationTitle("Detail") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } } } struct SheetView: View { var body: some View { NavigationStack { Text("Sheet (separate stack)") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.gray) .navigationTitle("Sheet") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } } } } Has anyone else seen this or found a workaround outside of disabling this background completely with .sharedBackgroundVisibility(.hidden)? I have filed a bug report under FB22141183
1
0
311
1w
ShareLink "Save Image" action dismisses presenting view after saving
When using ShareLink in SwiftUI to share an image, the “Save Image” action dismisses not only the share sheet but also the presenting SwiftUI view. The behavior differs depending on whether the photo library permission alert appears. Observed behavior: The first time the user taps Save Image, the system permission alert appears. After granting permission, the image saves successfully and the share sheet dismisses normally. On subsequent attempts, the image is saved successfully, but both the share sheet and the presenting view are dismissed unexpectedly. Expected behavior: After saving the image, only the share sheet should dismiss. The presenting SwiftUI view should remain visible. Steps to Reproduce Present a SwiftUI view using .sheet. Inside that view, add a ShareLink configured to export a PNG image using Transferable. Tap the ShareLink button. Choose Save Image. Grant permission the first time (if prompted). Repeat the action. Result: On subsequent saves, the share sheet dismisses and the presenting view is dismissed as well. Sample code ` internal import System import UniformTypeIdentifiers import SwiftUI struct RootView: View { @State private var isPresented: Bool = false var body: some View { ZStack { Color.white Button("Show parent view") { isPresented = true } } .sheet(isPresented: $isPresented) { ParentView() } } } struct ParentView: View { @State private var isPresented: Bool = false var body: some View { NavigationStack { ZStack { Color.red.opacity(0.5) } .toolbar { ToolbarItem() { let name = "\(UUID().uuidString)" let image = UIImage(named: "after")! return ShareLink( item: ShareableImage(image: image, fileName: name), preview: SharePreview( name, image: Image(uiImage: image) ) ) { Image(uiImage: UIImage(resource: .Icons.share24)) .resizable() .foregroundStyle(Color.black) .frame(width: 24, height: 24) } } } } } } struct ShareableImage: Transferable { let image: UIImage let fileName: String static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: .png) { item in let fileURL = FileManager.default.temporaryDirectory .appendingPathComponent(item.fileName) .appendingPathExtension("png") guard let data = item.image.pngData() else { throw NSError(domain: "ImageEncodingError", code: 0) } try data.write(to: fileURL) return SentTransferredFile(fileURL) } } } `
4
0
124
1w
Scrolling to row with a pinned header view
Hi, I have a list with section headers as pinned views. I'm trying to programmatically scroll to a view inside a section using a proxy.scrollTo(id, anchor: .top). I was expecting the view to be aligned to the top of the scroll view but after the pinned header. Instead, it's aligned to the top of the scroll view overlapping with the header, hiding most of the row. Here is a code snippet to reproduce: import SwiftUI struct ContentView: View { var body: some View { ScrollViewReader { proxy in ScrollView { LazyVStack( pinnedViews: .sectionHeaders ){ ForEach(1...10, id: \.self) { count1 in Section(content: { Text("First row") .id("\(count1), row1") Text("second row") Text("third row") }, header: { Text("Section \(count1)").font(.title) .background(.red) }) } } } .safeAreaInset(edge: .bottom) { Button("Tap me") { proxy.scrollTo("3, row1", anchor: .top) } .padding() } } } } Any idea how this could be solved?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
31
1w
A Summary of the WWDC25 Group Lab - SwiftUI
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for SwiftUI. What's your favorite new feature introduced to SwiftUI this year? The new rich text editor, a collaborative effort across multiple Apple teams. The safe area bar, simplifying the management of scroll view insets, safe areas, and overlays. NavigationLink indicator visibility control, a highly requested feature now available and back-deployed. Performance improvements to existing components (lists, scroll views, etc.) that come "for free" without requiring API adoption. Regarding performance profiling, it's recommended to use the new SwiftUI Instruments tool when you have a good understanding of your code and notice a performance drop after a specific change. This helps build a mental map between your code and the profiler's output. The "cause-and-effect graph" in the tool is particularly useful for identifying what's triggering expensive view updates, even if the issue isn't immediately apparent in your own code. My app is primarily UIKit-based, but I'm interested in adopting some newer SwiftUI-only scene types like MenuBarExtra or using SwiftUI-exclusive features. Is there a better way to bridge these worlds now? Yes, "scene bridging" makes it possible to use SwiftUI scenes from UIKit or AppKit lifecycle apps. This allows you to display purely SwiftUI scenes from your existing UIKit/AppKit code. Furthermore, you can use SwiftUI scene-specific modifiers to affect those scenes. Scene bridging is a great way to introduce SwiftUI into your apps. This also allows UIKit apps brought to Vision OS to integrate volumes and immersive spaces. It's also a great way to customize your experience with Assistive Access API. Can you please share any bad practices we should avoid when integrating Liquid Glass in our SwiftUI Apps? Avoid these common mistakes when integrating liquid glass: Overlapping Glass: Don't overlap liquid glass elements, as this can create visual artifacts. Scrolling Content Collisions: Be cautious when using liquid glass within scrolling content to prevent collisions with toolbar and navigation bar glass. Unnecessary Tinting: Resist the urge to tint the glass for branding or other purposes. Liquid glass should primarily be used to draw attention and convey meaning. Improper Grouping: Use the GlassEffectContainer to group related glass elements. This helps the system optimize rendering by limiting the search area for glass interactions. Navigation Bar Tinting: Avoid tinting navigation bars for branding, as this conflicts with the liquid glass effect. Instead, move branding colors into the content of the scroll view. This allows the color to be visible behind the glass at the top of the view, but it moves out of the way as the user scrolls, allowing the controls to revert to their standard monochrome style for better readability. Thanks for improving the performance of SwiftUI List this year. How about LazyVStack in ScrollView? Does it now also reuse the views inside the stack? Are there any best practices for improving the performance when using LazyVStack with large number of items? SwiftUI has improved scroll performance, including idle prefetching. When using LazyVStack with a large number of items, ensure your ForEach returns a static number of views. If you're returning multiple views within the ForEach, wrap them in a VStack to signal to SwiftUI that it's a single row, allowing for optimizations. Reuse is handled as an implementation detail within SwiftUI. Use the performance instrument to identify expensive views and determine how to optimize your app. If you encounter performance issues or hitches in scrolling, use the new SwiftUI Instruments tool to diagnose the problem. Implementing the new iOS 26 tab bar seems to have very low contrast when darker content is underneath, is there anything we should be doing to increase the contrast for tab bars? The new design is still in beta. If you're experiencing low contrast issues, especially with darker content underneath, please file feedback. It's generally not recommended to modify standard system components. As all apps on the platform are adopting liquid glass, feedback is crucial for tuning the experience based on a wider range of apps. Early feedback, especially regarding contrast and accessibility, is valuable for improving the system for all users. If I’m starting a new multi-platform app (iOS/iPadOS/macOS) that will heavily depend on UIKit/AppKit for the core structure and components (split, collection, table, and outline views), should I still use SwiftUI to manage the app lifecycle? Why? Even if your new multi-platform app heavily relies on UIKit/AppKit for core structure and components, it's generally recommended to still use SwiftUI to manage the app lifecycle. This sets you up for easier integration of SwiftUI components in the future and allows you to quickly adopt new SwiftUI features. Interoperability between SwiftUI and UIKit/AppKit is a core principle, with APIs to facilitate going back and forth between the two frameworks. Scene bridging allows you to bring existing SwiftUI scenes into apps that use a UIKit lifecycle, or vice versa. Think of it not as a binary choice, but as a mix of whatever you need. I’d love to know more about the matchedTransitionSource API you’ve added - is it a native way to have elements morph from a VStack to a sheet for example? What is the use case for it? The matchedTransitionSource API helps connect different views during transitions, such as when presenting popovers or other presentations from toolbar items. It's a way to link the user interaction to the presented content. For example, it can be used to visually connect an element in a VStack to a sheet. It can also be used to create a zoom effect where an element appears to enlarge, and these transitions are fully interactive, allowing users to swipe. It creates a nice, polished experience for the user. Support for this API has been added to toolbar items this year, and it was already available for standard views.
Topic: UI Frameworks SubTopic: SwiftUI
Replies
1
Boosts
0
Views
1.3k
Activity
Jun ’25
IOS Swift touch screen issue
MyOwnKeyboard Pad app has 4 text views with textfields that use touch screen for editing. There is one view, Compose, that has a textfield and a textview (UIRepresentable). The app enters text into the view using textfield buttons. The app has total control of editing. When entering text if the screen is touched it conflicts the cursor position and creates an "out of bounds" failure. In that view the app does not need any touch events. I need a method in UIRepresentable to disable the touch event. I am not familiar with UIRepresentable as this code was provided by Apple to solve a 16 bit unicode character issue. What would be the code to disable touch events in the UIRepresentable compose view. The app is free for a while until this problem is fixed. It is for iPads 11"+ . The name in the app store is MyOwnKeyboard Pad. I know some great engineer will find the answer. DTS tried. Thanks to all, maybe I'll sell some. Charlie 25mar26
Replies
1
Boosts
0
Views
103
Activity
12h
ScrollView clipping nav title in iOS 26?
When using a ScrollView inside some sort of navigation (stack or split view), large navigation titles seem to get clipped to the width of the scroll content for some reason? Minimal example: struct ContentView: View { var body: some View { NavigationStack { ScrollView { Text("Scroll Content") } .navigationTitle("Navigation Title") } } } Results in: Is this a bug in the beta, or has something changed and now I’m doing things wrong?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
3
Boosts
0
Views
241
Activity
21h
Localization in Swift macOS console Apps.
Is it possible to build localization into console apps, developed in SwiftUI in Xcode26. I have created a catalog, (.xcstrings file) with an English and fr-CA string. I have tried to display the French text without success. I am using the console app to test a package which also has English/French text. English text works fine in both package and the console main, but I cannot generate the French. From what I can discover so far it's not possible without bundling it as a .app, (console app). Looking for anyone who has crossed this bridge.
Replies
7
Boosts
0
Views
259
Activity
1d
SwiftUI Chart scrolling on macOS
I'm running macOS 26.3 and using Xcode 26.4. I'm trying to create a SwiftUI Chart that can scroll horizontally. In the SwiftUI Preview, and also running the app on macOS, the chart displays a scrollbar, but the scrollbar does not respond to mouse interaction (dragging the scrollbar, or clicking in the gutters on either side of the scrollbar). Here's the sample code: import SwiftUI import Charts private struct DataPoint: Identifiable { let id: Int let x: Double let value: Double } struct ContentView: View { private let points: [DataPoint] = (0..<60).map { index in let wave = sin(Double(index) * 0.28) * 18 let trend = Double(index) * 0.35 return DataPoint(id: index, x: Double(index), value: 60 + wave + trend) } var body: some View { Chart(points) { point in BarMark( x: .value("Data Point", point.x), y: .value("Value", point.value) ) .foregroundStyle(.blue.gradient) } .chartScrollableAxes(.horizontal) // Doesn't work: // .scrollIndicators(.hidden) // .never also does not work .chartXVisibleDomain(length: 20) .padding() } } #Preview { ContentView() }
Replies
3
Boosts
0
Views
100
Activity
1d
NavigationLink selection in DisclosureGroup not working with .draggable modifier
NavigationLink selection in DisclosureGroup not working with .draggable modifier This was recently also posted here: https://stackoverflow.com/questions/79914290/ I am playing around with a tree data structure with folders and entries.I would like to add dragging of entries and folders between folders, using .draggable and dropDestination. In my current code, dragging works, but selection of entries no longer works, except if I click outside of the Text If I comment out .draggable(subfolder.name) in func FolderRow(), selection works as expected. How can I make sure both selection and drag and drop works for both folders and entries? I also tried using Transferable and Codable, but I get the same result. Here is an MRE: import SwiftData import SwiftUI @Model final class Folder { @Attribute(.unique) var name: String // Parent var parentFolder: Folder? // Child folders @Relationship(deleteRule: .cascade, inverse: \Folder.parentFolder) var subfolders: [Folder] = [] // Leaf entries @Relationship(deleteRule: .cascade, inverse: \Entry.folder) var entries: [Entry] = [] init(name: String, parentFolder: Folder? = nil) { self.name = name self.parentFolder = parentFolder } } @Model final class Entry { @Attribute(.unique) var name: String var detail: String var folder: Folder? // recursive relationship init(name: String, detail: String) { self.name = name self.detail = detail } } @main struct TestMacApp: App { var body: some Scene { WindowGroup { SidebarView() .modelContainer(for: Folder.self) } } } struct SidebarView: View { @Environment(\.modelContext) private var context @Query(filter: #Predicate<Folder> { $0.parentFolder == nil }) private var rootFolders: [Folder] var body: some View { NavigationSplitView { List { ForEach(rootFolders) { folder in FolderRow(folder: folder) .draggable(folder.name) } } } detail: { Text("detail") } .onAppear { seed() } } } struct FolderRow: View { @Environment(\.modelContext) private var context var folder: Folder @State private var isExpanded: Bool = true var body: some View { DisclosureGroup(isExpanded: $isExpanded) { // Subfolders ForEach(folder.subfolders) { subfolder in FolderRow(folder: subfolder) .draggable(subfolder.name) // disabling this line fixes the selection } // Entries (leaf nodes) ForEach(folder.entries) { entry in NavigationLink(destination: EntryDetail(entry: entry)) { EntryRow(entry: entry) } .draggable(entry.name) } } label: { Label(folder.name, systemImage: "folder") } .dropDestination(for: String.self) { names, _ in return handleDrop(of: names) } } } struct EntryRow: View { var entry: Entry var body: some View { Text(entry.name) } } struct EntryDetail: View { var entry: Entry var body: some View { Text(entry.detail) } } extension FolderRow { private func handleDrop(of names: [String]) -> Bool { do { for name in names { if let droppedEntry = try context.fetchFilteredModel(filter: #Predicate<Entry> { x in x.name == name }) { droppedEntry.folder = folder print("dropped \(droppedEntry.name) on \(folder.name)") } else if let droppedFolder = try context.fetchFilteredModel(filter: #Predicate<Folder> { x in x.name == name }) { if droppedFolder.parentFolder != nil && droppedFolder != folder { droppedFolder.parentFolder = folder print("dropped \(droppedFolder.name) on \(folder.name)") } } } return true } catch { debugPrint(error.localizedDescription) return false } } } extension SidebarView { private func seed() { do { // delete current models for folder: Folder in try context.fetchAllModels() { context.delete(folder) } try context.save() let rootFolder = Folder(name: "Root") let entry1 = Entry(name: "One", detail: "Detail One") let entry2 = Entry(name: "Two", detail: "Detail Two") rootFolder.entries.append(contentsOf: [entry1, entry2]) let subFolder1 = Folder(name: "Sub1", parentFolder: rootFolder) let entry3 = Entry(name: "Three", detail: "Detail Three") let entry4 = Entry(name: "Four", detail: "Detail Four") subFolder1.entries.append(contentsOf: [entry3, entry4]) let subFolder2 = Folder(name: "Sub2", parentFolder: rootFolder) let entry5 = Entry(name: "Five", detail: "Detail Five") let entry6 = Entry(name: "Six", detail: "Detail Six") subFolder2.entries.append(contentsOf: [entry5, entry6]) context.insert(rootFolder) } catch { debugPrint(error) } } } extension ModelContext { // convenience methods func fetchAllModels<M>() throws -> [M] where M: PersistentModel { let fetchDescriptor = FetchDescriptor<M>() return try fetch(fetchDescriptor) } func fetchFilteredModels<M>(filter: Predicate<M>) throws -> [M] where M: PersistentModel { let fetchDescriptor = FetchDescriptor<M>(predicate: filter) return try fetch(fetchDescriptor) } func fetchFilteredModel<M>(filter: Predicate<M>) throws -> M? where M: PersistentModel { return try fetchFilteredModels(filter: filter).first } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
1
Boosts
0
Views
161
Activity
1d
Combining NavigationSplitView and TabView in iOS 18
Hi folks, I've used a NavigationSplitView within one of the tabs of my app since iOS 16, but with the new styling in iOS 18 the toolbar region looks odd. In other tabs using e.g. simple stacks, the toolbar buttons are horizontally in line with the new tab picker, but with NavigationSplitView, the toolbar leaves a lot of empty space at the top (see below). Is there anything I can do to adjust this, or alternatively, continue to use the old style? Thanks!
Replies
13
Boosts
3
Views
2.9k
Activity
1d
On macOS Settings window navigation bar item is in the center
Hi, Overview I have a Mac app with a settings window. When I add a button it is added to the center. I want it on the trailing edge, I even tried adding it as confirmationAction but doesn’t work. Screenshot Feedback FB21374186 Steps to reproduce Run the project on mac Open the app's settings by pressing ⌘ , Notice that the Save button is in the center instead of the trailing edge Code App import SwiftUI @main struct SettingsToolbarButtonBugApp: App { var body: some Scene { WindowGroup { ContentView() } Settings { SettingsView() .frame(width: 300, height: 400) } } } SettingsView import SwiftUI struct SettingsView: View { var body: some View { NavigationStack { Form { Text("Settings window") } .toolbar { ToolbarItem(placement: .confirmationAction) { // Save button is the center instead of trailing edge Button("Save") {} } } .navigationTitle("Settings") } } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
1
Boosts
0
Views
173
Activity
2d
MapKit in SwiftUI
Anyone worked with MapKit's MapCameraPosition in SwiftUI? I'm building a navigation app and ran into a limitation I can't find a clean solution for when using .userLocation(followsHeading: true) MapKit takes full control of the camera, smooth heading tracking, follows the user automatically. Perfect. But there's no way to set a custom pitch (tilt) on it. The only initializer available is... .userLocation(followsHeading: true, fallback: .automatic) No pitch, no distance parameters.... The workaround I found is setting .camera(MapCamera(..., pitch: 60)) first, waiting 200ms, then switching to .userLocation(followsHeading: true), MapKit inherits the pitch from the rendered camera state before handing off to user tracking.... It works, but it's clearly exploiting an undocumented behaviour in MapKit's state machine rather than a proper API Has anyone found a cleaner way to achieve this? Or is UIViewRepresentable wrapping MKMapView the only proper solution? It would be awesome to have something like this cameraPosition = .userLocation( followsHeading: true, pitch: 60, distance: 800, fallback: .automatic )
Replies
1
Boosts
0
Views
114
Activity
2d
How to recreate Apple Music mini player transition in SwiftUI
Hello, I am building an audio player app in SwiftUI and trying to recreate the behavior of Apple Music's mini player and full player. I'm struggling to get the animation to seamlessly transition between the mini player and the full player. Currently, it feels disconnected and doesn't resemble the smooth animation seen in Apple Music. What I want to achieve: Full player that expands/collapses from/to the mini player Smooth artwork transition between both states Drag down to collapse the full player Support both newer APIs like tabViewBottomAccessory and older iOS versions Questions: What is the best way to build this transition in SwiftUI? Should I use matchedGeometryEffect or something else? Should this be a custom container instead of fullScreenCover? How would you support both new and older iOS versions? What is the best way to implement drag to dismiss? Thanks for any help! Example code: struct ContentView: View { @State private var isFullPlayerPresented = false var body: some View { TabView { Tab("Home", systemImage: "house") { Text("Home") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.green) } Tab("Library", systemImage: "rectangle.stack.fill") { Text("Library") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.brown) } } .tabViewBottomAccessory(isEnabled: !isFullPlayerPresented) { MiniPlayerView(isFullPlayerPresented: $isFullPlayerPresented) } .fullScreenCover(isPresented: $isFullPlayerPresented) { // Maybe it's not a full screen cover presentation in Apple Music? FullPlayerView(isFullPlayerPresented: $isFullPlayerPresented) } } } Mini player: struct MiniPlayerView: View { @Binding var isFullPlayerPresented: Bool var body: some View { Button { isFullPlayerPresented = true } label: { HStack { Image(systemName: "photo") .resizable() .scaledToFit() .frame(width: 30, height: 30) .clipShape(.rect(cornerRadius: 8)) Spacer() Text("Tap to open full player") Spacer() Button("", systemImage: "play.fill", action: {}) } .padding(.horizontal) .padding(.vertical, 4) } .foregroundStyle(.white) } } Full player: struct FullPlayerView: View { @Binding var isFullPlayerPresented: Bool var body: some View { // This art work needs to snaps to the artwork in mini player Image(systemName: "photo") .resizable() .scaledToFit() .frame(width: 250, height: 250) .clipShape(.rect(cornerRadius: 20)) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.red) .overlay(alignment: .topTrailing) { Button(role: .close) { isFullPlayerPresented = false } .foregroundStyle(.white) .padding() } } }
Replies
0
Boosts
0
Views
119
Activity
3d
Wrong position of searchable component on first render
Hey all, I found a weird behaviour with the searchable component. I created a custom bottom nav bar (because I have custom design in my app) to switch between screens. On one screen I display a List component with the searchable component. Whenever I enter the search screen the first time, the searchable component is displayed at the bottom. This is wrong. It should be displayed at the top under the navigationTitle. When I enter the screen a second time, everything is correct. This behaviour can be reproduced on all iOS 26 versions on the simulator and on a physical device with debug and release build. On iOS 18 everything works fine. Steps to reproduce: Cold start of the app Click on Search TabBarIcon (searchable wrong location) Click on Home TabBarIcon Click on Search TabBarIcon (searchable correct location) Simple code example: import SwiftUI struct ContentView: View { @State var selectedTab: Page = Page.main var body: some View { NavigationStack { ZStack { VStack { switch selectedTab { case .main: MainView() case .search: SearchView() } } VStack { Spacer() VStack(spacing: 0) { HStack(spacing: 0) { TabBarIcon(iconName: "house", selected: selectedTab == .main, displayName: "Home") .onTapGesture { selectedTab = .main } TabBarIcon(iconName: "magnifyingglass", selected: selectedTab == .search, displayName: "Search") .onTapGesture { selectedTab = .search } } .frame(maxWidth: .infinity) .frame(height: 55) .background(Color.gray) } .ignoresSafeArea(.all, edges: .bottom) } } } } } struct TabBarIcon: View { let iconName: String let selected: Bool let displayName: String var body: some View { ZStack { VStack { Image(systemName: iconName) .resizable() .renderingMode(.template) .aspectRatio(contentMode: .fit) .foregroundColor(Color.black) .frame(width: 22, height: 22) Text(displayName) .font(Font.system(size: 10)) } } .frame(maxWidth: .infinity) } } enum Page { case main case search } struct MainView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .navigationTitle("Home") } } struct SearchView: View { @State private var searchText = "" let items = [ "Apple", "Banana", "Pear", "Strawberry", "Orange", "Peach", "Grape", "Mango" ] var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.localizedCaseInsensitiveContains(searchText) } } } var body: some View { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") } }
Replies
4
Boosts
0
Views
243
Activity
3d
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
Replies
0
Boosts
0
Views
31
Activity
4d
onDisappear not called when closing a document on macOS (Designed for iPad), works on iPad
When running a SwiftUI DocumentGroup app on macOS designed for iPad, onDisappear is not called when closing a document, and deinit of state objects owned by a ContentView is not invoked. This behavior works as expected on iPad. @main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: MyDocument()) { file in ContentView(document: file.$document) .onDisappear { print("This isn't called on macOS Designed For iPad, but is on iPad when closing a document.") } } } } It is my understanding that for a macOS designed for iPad these lifecycle events would behave the same - otherwise there appears to be no way to detect if a document has closed on macOS.
Replies
1
Boosts
0
Views
64
Activity
4d
iPadOS 26 Crash when num pad with floating keyboard in presented view
Build the sample code below, type something in the textfield (make sure the num pad is a popup and that the text keyboard is floating). And tap multiple times outside of the textfield in the sheet. That will lead to the crash: *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x60000179cec0 "UIView:0x103c52fe0.top"> and <NSLayoutYAxisAnchor:0x6000017e0800 "_UIRemoteKeyboardPlaceholderView:0x103baa240.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.' terminating due to uncaught exception of type NSException CoreSimulator 1051.17.8 - Device: iPad Pro 13-inch (M5) (655000D7-41BC-4B13-BD07-BBA80D892E97) - Runtime: iOS 26.2 (23C54) - DeviceType: iPad Pro 13-inch (M5) Does anyone have the slightest idea of a workaround? I can't find one. import SwiftUI struct ContentView: View { var body: some View { Text("Content") .sheet(isPresented: .constant(true)) { PresentedView() } } } struct PresentedView: View { @State private var text = "" var body: some View { ScrollView { VStack { TextField("Placeholder", text: $text) .keyboardType(.numberPad) } .padding(80) } } } See here for discussion and video to reproduce: https://stackoverflow.com/questions/79905933/ipados-26-crash-when-floating-num-pad-in-presented-view
Replies
0
Boosts
1
Views
14
Activity
5d
Unwanted animation of navbar controls
What could cause the issue shown on the gif. At first I though clean build folder helps. But when you close the main window and open it after some time it gets back to this state. The whole set of elements in the navbar starts shifting to the right and it continues infinitely 15.6.1 (24G90) Swift 6.1.2
Replies
2
Boosts
0
Views
66
Activity
5d
Zoom navigation transitions for tabViewBottomAccessory are not working in SwiftUI with ObservableObject or Observable
The zoom navigation transition with matchedTransitionSource in tabViewBottomAccessory does not work when a Published var in an ObservableObjector Observable gets changed. Here is an minimal reproducible example with ObservableObject: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace @StateObject private var viewModel = ViewModel() // @State private var isPresented = false var body: some View { TabView { Button { viewModel.isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $viewModel.isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { viewModel.isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } } However, when using only a State property everything works: import SwiftUI import Combine private final class ViewModel: ObservableObject { @Published var isPresented = false } struct ContentView: View { @Namespace private var namespace // @StateObject private var viewModel = ViewModel() @State private var isPresented = false var body: some View { TabView { Button { isPresented = true } label: { Text("Start") } .tabItem { Image(systemName: "house") Text("Home") } Text("Search") .tabItem { Image(systemName: "magnifyingglass") Text("Search") } Text("Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .sheet(isPresented: $isPresented) { Text("Sheet") .presentationDragIndicator(.visible) .navigationTransition(.zoom(sourceID: "tabViewBottomAccessoryTransition", in: namespace)) } .tabViewBottomAccessory { Button { isPresented = true } label: { Text("BottomAccessory") } .matchedTransitionSource(id: "tabViewBottomAccessoryTransition", in: namespace) } } }
Replies
7
Boosts
1
Views
383
Activity
5d
Bottom toolbar Button truncated on Mac Catalyst 26
On Mac Catalyst 26, a Button bar item in a bottom toolbar look squished. This happens only when the "Mac Catalyst Interface" option is set to "Optimize for Mac". When it is set to "Scale to match iPad", the buttons look fine. For example, in the screenshots below, the text button should say "Press Me", instead of "…" A simple reproducible snippet and a screenshot below. The toolbar button comparison between "Scale to match iPad" and "Optimize for Mac" are shown. Optimize for Mac Scale to match iPad import SwiftUI struct ContentView: View { @State private var selectedItem: String? = "Item 1" let items = ["Item 1", "Item 2"] var body: some View { NavigationSplitView { List(items, id: \.self, selection: $selectedItem) { item in Text(item) } .navigationTitle("Items") } detail: { if let selectedItem = selectedItem { Text("Detail view for \(selectedItem)") .toolbar { ToolbarItemGroup(placement: .bottomBar) { Text("Hello world") Spacer() Button("Press Me") { } Spacer() Button { } label: { Image(systemName: "plus") .imageScale(.large) } } } } else { Text("Select an item") } } } }
Replies
3
Boosts
2
Views
439
Activity
5d
Charts performance issue
Hi, I want to recreate a chart from Apple Health and I have code like this. When I scroll - especially the week and month charts, there are performance issues. If I remove .chartScrollPosition(x: $scrollChartPosition), it runs smoothly, but I need to know which part of the chart is currently displayed. Can you help me? import Charts import SwiftUI struct MacroChartView: View { var selectedRange: ChartRange var binnedPoints: [MacroBinPoint] @State private var scrollChartPosition: Date = .now var body: some View { VStack { Text("\(selectedRange.rangeLabel(for: scrollChartPosition))") Chart(binnedPoints) { point in BarMark( x: .value("Date", point.date, unit: selectedRange.binComponent), y: .value("Calories", point.calories) ) } .frame(height: 324) .chartXVisibleDomain(length: selectedRange.visibleDomainLength()) .chartScrollableAxes(.horizontal) .chartScrollPosition(x: $scrollChartPosition) .chartScrollTargetBehavior(.valueAligned(matching: selectedRange.scrollAlignmentComponents)) .chartXAxis { switch selectedRange { case .week: AxisMarks(values: .stride(by: .day)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.weekday(.abbreviated)) } case .month: AxisMarks(values: .stride(by: .weekOfYear)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.day()) } case .halfYear: AxisMarks(values: .stride(by: .month)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.month(.abbreviated)) } case .year: AxisMarks(values: .stride(by: .month)) { date in AxisGridLine() AxisTick() AxisValueLabel(format: .dateTime.month(.abbreviated)) } } } } } } enum MeasurementHistoryMode { case macros case comparisons } enum MacroKindToDisplay { case protein, fat, carbs } enum MacrosDisplayMode: Equatable { case all case single(MacroKindToDisplay) } enum ChartRange: String, CaseIterable { case week = "T" case month = "M" case halfYear = "6M" case year = "R" var binComponent: Calendar.Component { switch self { case .week, .month: return .day case .halfYear: return .weekOfYear case .year: return .month } } var scrollAlignmentComponents: DateComponents { switch self { case .week: return DateComponents(hour: 0, minute: 0, second: 0) case .month: return DateComponents(hour: 0) case .halfYear: return DateComponents(weekday: 1) case .year: return DateComponents(day: 1) } } func visibleDomainLength() -> Int { switch self { case .week: return 7 * 24 * 60 * 60 case .month: return 31 * 24 * 60 * 60 case .halfYear: return 6 * 31 * 24 * 60 * 60 case .year: return 12 * 31 * 24 * 60 * 60 } } func start(for date: Date) -> Date { let cal = Calendar.current switch self { case .week, .month: return cal.startOfDay(for: date) case .halfYear: return cal.dateInterval(of: .weekOfYear, for: date)?.start ?? cal.startOfDay(for: date) case .year: return cal.dateInterval(of: .month, for: date)?.start ?? cal.startOfDay(for: date) } } func rangeLabel(for start: Date) -> String { let end = start.addingTimeInterval(TimeInterval(visibleDomainLength())) let f = DateFormatter() f.dateFormat = Calendar.current.isDate(start, inSameDayAs: end) ? "MMM d" : "MMM d" return Calendar.current.isDate(start, inSameDayAs: end) ? f.string(from: start) : "\(f.string(from: start)) – \(f.string(from: end))" } } struct MacrosPoint: Identifiable { var id: Date { date } let date: Date let calories: Double let proteinInGrams: Double let carbsInGrams: Double let fatInGrams: Double } struct MacroBinPoint: Identifiable { var id: Date { date } let date: Date let calories: Double let proteinKcal: Double let carbsKcal: Double let fatKcal: Double } func bin(points: [MacrosPoint], for period: ChartRange) -> [MacroBinPoint] { let grouped = Dictionary(grouping: points) { point in period.start(for: point.date) } let bins = grouped.map { (start, items) -> MacroBinPoint in var calories = items.reduce(0) { $0 + $1.calories } var proteinKcal = items.reduce(0) { $0 + $1.proteinInGrams * 4 } var carbsKcal = items.reduce(0) { $0 + $1.carbsInGrams * 4 } var fatKcal = items.reduce(0) { $0 + $1.fatInGrams * 9 } calories /= Double(items.count) proteinKcal /= Double(items.count) carbsKcal /= Double(items.count) fatKcal /= Double(items.count) return MacroBinPoint(date: start, calories: calories, proteinKcal: proteinKcal, carbsKcal: carbsKcal, fatKcal: fatKcal) } .sorted { $0.date < $1.date } return bins } struct ExampleData { static let macrosPoints: [MacrosPoint] = [ MacrosPoint(date: Date(timeIntervalSince1970: 1687949774), calories: 1895, proteinInGrams: 115, carbsInGrams: 192, fatInGrams: 72),... ]
Replies
0
Boosts
0
Views
104
Activity
1w
iOS 26: Toolbar button background flashes black during NavigationStack transitions (dark mode)
I’m seeing a visual glitch with toolbar buttons when building with Xcode 26 for iOS 26. During transitions (both pushing in a NavigationStack and presenting a .sheet with its own NavigationStack), the toolbar button briefly flashes the wrong background colour (black in dark mode, white in light mode) before animating to the correct Liquid Glass appearance. This happens even in a minimal example and only seems to affect system toolbar buttons. A custom view with .glassEffect() doesn’t have the issue. I’ve tried: .tint(...), UINavigationBarAppearance/UIToolbarAppearance, and setting backgrounds on hosting/nav/window but none of those made any difference. Here’s a minimal reproducible example: import SwiftUI struct ContentView: View { @State private var showingSheet = false var body: some View { NavigationStack { List { NavigationLink("Push (same stack — morphs)") { DetailView() } Button("Sheet (separate stack — flashes)") { showingSheet = true } } .navigationTitle("Root") .scrollContentBackground(.hidden) .background(.gray) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } .sheet(isPresented: $showingSheet) { SheetView() } } } } struct DetailView: View { var body: some View { Text("Detail (same stack)") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.gray) .navigationTitle("Detail") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } } } struct SheetView: View { var body: some View { NavigationStack { Text("Sheet (separate stack)") .frame(maxWidth: .infinity, maxHeight: .infinity) .background(.gray) .navigationTitle("Sheet") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Action") {} } } } } } Has anyone else seen this or found a workaround outside of disabling this background completely with .sharedBackgroundVisibility(.hidden)? I have filed a bug report under FB22141183
Replies
1
Boosts
0
Views
311
Activity
1w
ShareLink "Save Image" action dismisses presenting view after saving
When using ShareLink in SwiftUI to share an image, the “Save Image” action dismisses not only the share sheet but also the presenting SwiftUI view. The behavior differs depending on whether the photo library permission alert appears. Observed behavior: The first time the user taps Save Image, the system permission alert appears. After granting permission, the image saves successfully and the share sheet dismisses normally. On subsequent attempts, the image is saved successfully, but both the share sheet and the presenting view are dismissed unexpectedly. Expected behavior: After saving the image, only the share sheet should dismiss. The presenting SwiftUI view should remain visible. Steps to Reproduce Present a SwiftUI view using .sheet. Inside that view, add a ShareLink configured to export a PNG image using Transferable. Tap the ShareLink button. Choose Save Image. Grant permission the first time (if prompted). Repeat the action. Result: On subsequent saves, the share sheet dismisses and the presenting view is dismissed as well. Sample code ` internal import System import UniformTypeIdentifiers import SwiftUI struct RootView: View { @State private var isPresented: Bool = false var body: some View { ZStack { Color.white Button("Show parent view") { isPresented = true } } .sheet(isPresented: $isPresented) { ParentView() } } } struct ParentView: View { @State private var isPresented: Bool = false var body: some View { NavigationStack { ZStack { Color.red.opacity(0.5) } .toolbar { ToolbarItem() { let name = "\(UUID().uuidString)" let image = UIImage(named: "after")! return ShareLink( item: ShareableImage(image: image, fileName: name), preview: SharePreview( name, image: Image(uiImage: image) ) ) { Image(uiImage: UIImage(resource: .Icons.share24)) .resizable() .foregroundStyle(Color.black) .frame(width: 24, height: 24) } } } } } } struct ShareableImage: Transferable { let image: UIImage let fileName: String static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: .png) { item in let fileURL = FileManager.default.temporaryDirectory .appendingPathComponent(item.fileName) .appendingPathExtension("png") guard let data = item.image.pngData() else { throw NSError(domain: "ImageEncodingError", code: 0) } try data.write(to: fileURL) return SentTransferredFile(fileURL) } } } `
Replies
4
Boosts
0
Views
124
Activity
1w
Scrolling to row with a pinned header view
Hi, I have a list with section headers as pinned views. I'm trying to programmatically scroll to a view inside a section using a proxy.scrollTo(id, anchor: .top). I was expecting the view to be aligned to the top of the scroll view but after the pinned header. Instead, it's aligned to the top of the scroll view overlapping with the header, hiding most of the row. Here is a code snippet to reproduce: import SwiftUI struct ContentView: View { var body: some View { ScrollViewReader { proxy in ScrollView { LazyVStack( pinnedViews: .sectionHeaders ){ ForEach(1...10, id: \.self) { count1 in Section(content: { Text("First row") .id("\(count1), row1") Text("second row") Text("third row") }, header: { Text("Section \(count1)").font(.title) .background(.red) }) } } } .safeAreaInset(edge: .bottom) { Button("Tap me") { proxy.scrollTo("3, row1", anchor: .top) } .padding() } } } } Any idea how this could be solved?
Topic: UI Frameworks SubTopic: SwiftUI
Replies
0
Boosts
0
Views
31
Activity
1w