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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Concentric corners not working
I want the gray view to have concentric corners with the device border. That works. Then I want the blue rectangle to have concentric corners with the gray view. That does not work. Instead the blue rectangle is also concentric with the device border. Once I add other content like a Text element, the corner radius breaks. How can I make this work? .containerShape does not take a ConcentricContainerShape. struct ContentView: View { var body: some View { List { Text("Content") } .overlay(alignment: .bottom) { content } .ignoresSafeArea(.all, edges: .bottom) } var content: some View { VStack(alignment: .leading) { Rectangle() .foregroundStyle(.blue) .frame(width: 100, height: 100) .clipShape(.rect(corners: .concentric, isUniform: true)) Text("Custom Container") } .padding(20) .frame(maxWidth: .infinity, alignment: .leading) .background(Color.gray, in: .rect(corners: .concentric, isUniform: true)) .padding(15) } }
2
0
74
2d
How to create an overlay with padding that ignores the safe area?
Was it always so tricky to ignore the bottom safe area? Seems like iOS 26 makes this much harder. I've tried many variations of ignoresSafeArea, safeAreaInset, safeAreaBar, etc. Nothing seems to work. As soon as I add padding, the bottom safe area crashes the party. This is what I want to achieve: This is what I get right now: struct ContentView: View { var body: some View { List { Text("Content") } .overlay(alignment: .bottom) { content } } var content: some View { VStack { Text("Custom Container") } .frame(maxWidth: .infinity) .frame(height: 400) .background(Color.gray, in: .rect(corners: .concentric, isUniform: true)) .padding(15) } }
3
0
82
3w
iOS 18 Subviews and Environment values
Hello 👋 I played with the iOS 18 Group(subviews:) APIs these days and I guess I'm missing a point. Environment values seems to not being passed to subviews when set within the Group(subviews:) API. See the following code: Is it intended to be that way ? How to propagate different values to different subviews in this case ? I heard of ContainerValues API but it seems to be a way to provide value at root level to access it during subview iteration. What I'm looking for is "insert"/"propagate" values to each subview during subview iteration. PS: This works but I have lost subview context this way (I'm out of the group). Thanks in advance for anyone answering this!
3
0
72
3w
Preventing a custom menu to close when the main window SwiftUI View is updating - (macOS App)
I reposted this issue from my previous post since I have a partial solution to it, and now have a more precise question. The previous post title was too broad. My app is not Document-based, the UI is written with SwiftUI and I had to implement the 'Open Recent' menu myself. The class RecentDiscsModel has a refresh() function that forces the new opened file to be seen in the menu. Without that, the app needed to be restarted to see them. (The files were appearing in the Dock menu, however.) My problem is, that when we open this 'Open Recent' menu, it closes when the UI is updating. My app being a Disc Player, the main and unique window UI is updating every second or more through many @Published properties from my AudioDiscPlayer class. I have no idea how to prevent this issue. @main struct MyApp: App @main struct MyApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @StateObject private var recentDiscsModel = RecentDiscsModel.shared var body: some Scene { Window("Player", id: "main-window") { PlayerView() } .commands { CommandGroup(replacing: .newItem) { } CommandGroup(after: .newItem) { Button("Open...") { NotificationCenter.default.post(name: .openDocumentRequested, object: nil) } .keyboardShortcut("O", modifiers: .command) if recentDiscsModel.recentDocs.isEmpty == false { Menu("Open Recent") { ForEach(NSDocumentController.shared.recentDocumentURLs, id: \.self) { url in Button(url.lastPathComponent) { global.insertDisc(at: url) } } Divider() Button("Clear Menu") { NSDocumentController.shared.clearRecentDocuments(nil) recentDiscsModel.refresh() } } } } PlayBackMenu() } } } class RecentDiscsModel: ObservableObject | The class that handles the live refresh of the 'Open Recent' menu class RecentDiscsModel: ObservableObject { static let shared = RecentDiscsModel() @Published private(set) var recentFiles: [URL] = [] private init() { refresh() } func refresh() { let newDocs = NSDocumentController.shared.recentDocumentURLs if newDocs != recentDocs { recentDocs = newDocs } } } class Globals: ObservableObject | This is the class that handling opening cueSheet file: class Globals: ObservableObject { static let shared = MCGlobals() init() {} @Published var errorMessage = "" @Published var errorDetails = "" @Published var showingErrorAlert = false func handleFileImport(result: Result<URL, Error>) { switch result { case .success(let url): guard url.startAccessingSecurityScopedResource() else { errorMessage = "Unable to access file" errorDetails = "Permission denied" showingErrorAlert = true return } defer { url.stopAccessingSecurityScopedResource() } insertDisc(at: url) case .failure(let error): errorMessage = "Failed to import file" errorDetails = error.localizedDescription showingErrorAlert = true } } func insertDisc(at url: URL, startPlayback: Bool = false) { do { try AudioDiscPlayer.shared.insertDisc(at: url, startPlayback: startPlayback) NSDocumentController.shared.noteNewRecentDocumentURL(url) } catch { let nsError = error as NSError errorMessage = nsError.localizedDescription let reason = nsError.localizedFailureReason ?? "" let recovery = nsError.localizedRecoverySuggestion ?? "" errorDetails = "\n\n\(reason)\n\n\(recovery)".trimmingCharacters(in: .whitespacesAndNewlines) showingErrorAlert = true } RecentDiscsModel.shared.refresh() } }
1
0
72
3w
SwiftUI's List backed by CoreData using @FetchRequest fails to update on iOS 26 when compiled with Xcode 26
Hey there! I've been tracking a really weird behavior with a List backed by @FetchRequest from CoreData. When I toggle a bool on the CoreData model, the first time it updates correctly, but if I do it a second time, the UI doesn't re-render as expected. This does not happen if I compile the app using Xcode 16 (targeting both iOS 18 and iOS 26), nor it happens when using Xcode 26 and targeting iOS 18. It only happens when building the app using Xcode 26 and running it on iOS 26. Here are two demos: the first one works as expected, when I toggle the state twice, both times updates. The second one, only on iOS 26, the second toggle fails to re-render. Demo (running from Xcode 16): Demo (running from Xcode 26): The code: import SwiftUI import CoreData @main struct CoreDataTestApp: App { let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)]) private var items: FetchedResults<Item> var body: some View { NavigationView { List { ForEach(items) { item in HStack { Text(item.timestamp!.formatted()) Image(systemName: item.isFavorite ? "heart.fill" : "heart").foregroundStyle(.red) }.swipeActions(edge: .leading, allowsFullSwipe: true) { Button(item.isFavorite ? "Unfavorite" : "Favorite", systemImage: item.isFavorite ? "heart" : "heart.fill") { toggleFavoriteStatus(item: item) } } } } .toolbar { ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { withAnimation { let newItem = Item(context: viewContext) newItem.timestamp = Date() newItem.isFavorite = Bool.random() try! viewContext.save() } } private func toggleFavoriteStatus(item: Item) { withAnimation { item.isFavorite.toggle() try! viewContext.save() } } } struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentContainer init() { container = NSPersistentContainer(name: "CoreDataTest") container.loadPersistentStores(completionHandler: { _, _ in }) container.viewContext.automaticallyMergesChangesFromParent = true } }
5
0
171
6d
Display .icon files in SwiftUI
Is there a way to display a .icon file in SwiftUI? I want to show the app icon in the app itself but exporting and including the app icon as a PNG feels redundant. This would consume a lot of unnecessary storage especially when including a lot of alternative app icons. There has to be a better way Otherwise I would file a feedback for that Thank you
0
5
71
3w
@State variable returns empty despite being set in .onAppear function
With the code below, JSON data is parsed and is stored in the variable data in the .onAppear function, however an empty set of data is passed to the Content view. How can that be fixed so that the JSON data passes to the DataView? struct ContentView: View { @State var data: [Data] @State var index: Int = 0 var body: some View { VStack { DataView(data: data[index]) } .onAppear { let filePath = Bundle.main.path(forResource: "data", ofType: "json") let url = URL(fileURLWithPath: filePath!) data = getData(url: url) } } func getData(url: URL) -> [Data] { do { let data = try Data(contentsOf: url) let jsonDecoded = try JSONDecoder().decode([Data].self, from: data) return jsonDecoded } catch let error as NSError { print("Fail: \(error.localizedDescription)") } catch { print("Fail: \(error)") } return [] } }
17
1
462
3w
SwiftUI preview failed, help!!!!!
When I update the macOS from 15.5 to 15.6, Preview error. 1、I try remove simulator cache, sdk 2、remove Xcode build cache 3、reinstall Xcode 4、try with this method https://byby.dev/uninstall-xcode#:%7E:text=Delete%20old%20simulators%20and%20devices,moving%20them%20to%20the%20Trash but all failed swiftui log.txt
4
0
132
2w
How to detect which entity was tapped?
Hi, I'm rewriting my game from SceneKit to RealityKit, and I'm having trouble implementing the following scenario: I tap on the iPhone screen to select an Entity that I want to drag. If an Entity was tapped, it should then be possible to drag it left, right, etc. SceneKit solution: func CGPointToSCNVector3(_ view: SCNView, depth: Float, point: CGPoint) -> SCNVector3 { let projectedOrigin = view.projectPoint(SCNVector3Make(0, 0, Float(depth))) let locationWithz = SCNVector3Make(Float(point.x), Float(point.y), Float(projectedOrigin.z)) return view.unprojectPoint(locationWithz) } and then I was calling: SCNView().hitTest(location, options: [SCNHitTestOption.firstFoundOnly:true]) the code was called inside of the UIPanGestureRecognizer in my UIViewController. Could I reuse that code or should I go with the SwiftUI approach - something like that: var body: some View { RealityView { .... } .gesture(TapGesture().onEnded { }) ? I already have this code: @State private var location: CGPoint? .onTapGesture { location in self.location = location } I'm trying to identify the entity that was tapped within the RealityView like that: RealityView { content in let box: ModelEntity = createBox() // for now there is only one box, however there will be many boxes content.add(box) let anchor = AnchorEntity(world: [0, 0, 0]) content.add(anchor) _ = content.subscribe(to: SceneEvents.Update.self) { event in //TODO: find tapped entity, so that it could be dragged inside of the DragGesture() } Any help would be appreciated. I also noticed that if I create a TapGesture like that: TapGesture(count: 1) .targetedToAnyEntity() and add it to my view using .gesture() then it is not triggered.
2
0
114
3w
What is the scroll edge effect supposed to look like now?
At WWDC the scroll edge effect was presented as a variable blur combined with a soft gradient. Since beta 4 the bottom scroll edge effect has no blur, the top bar sometimes has, but sometimes does not. Even in my own app I have two views with totally different results. This was not changed back in beta 5, so I assume this is not a bug but an intended change. It's hard to design for such a moving target. Especially the missing bottom blur looks bad in a lot of places in my app and I'm debating not shipping the new design if this does not get resolved. Is there any guidance how this effect is supposed to look now? At this point it just seems random and there's no way adjust the way it looks. Phone: Top blur, bottom no blur Settings: Top blur, bottom no blur Notes: No blur at all Music: No blur at all My own app: No top blur My own app: Top blur
4
1
115
1w
SwiftUI iOS 16 TabView PageTabViewStyle index behavior is wrong for right to left layoutDirection
TabView page control element has a bug on iOS 16 if tabview is configured as RTL with PageTabViewStyle. Found iOS 16 Issues: Page indicators display dots in reverse order (appears to treat layout as LTR while showing RTL) Index selection is reversed - tapping indicators selects wrong pages Using the page control directly to navigate eventually breaks the index binding The underlying index counting logic conflicts with the visual presentation iOS 18 Behavior: Works as expected with correct dot order and index selection. Xcode version: Version 16.3 (16E140) Conclusion: Confirmed broken on iOS 16 Confirmed working on iOS 18 iOS 17 and earlier versions not yet tested I've opened a feedback assistant ticket quite a while ago but there is no answer. There's a code example and a video there. Anyone else had experience with this particular bug? Here's the code: public struct PagingView<Content: View>: View { //MARK: - Public Properties let pages: (Int) -> Content let numberOfPages: Int let pageMargin: CGFloat @Binding var currentPage: Int //MARK: - Object's Lifecycle public init(currentPage: Binding<Int>, pageMargin: CGFloat = 20, numberOfPages: Int, @ViewBuilder pages: @escaping (Int) -> Content) { self.pages = pages self.numberOfPages = numberOfPages self.pageMargin = pageMargin _currentPage = currentPage } //MARK: - View's Layout public var body: some View { TabView(selection: $currentPage) { ForEach(0..<numberOfPages, id: \.self) { index in pages(index) .padding(.horizontal, pageMargin) } } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always)) .ignoresSafeArea() } } //MARK: - Previews struct ContentView: View { @State var currentIndex: Int = 0 var body: some View { ZStack { Rectangle() .frame(height: 300) .foregroundStyle(Color.gray.opacity(0.2)) PagingView( currentPage: $currentIndex.onChange({ index in print("currentIndex: ", index) }), pageMargin: 20, numberOfPages: 10) { index in ZStack { Rectangle() .frame(width: 200, height: 200) .foregroundStyle(Color.gray.opacity(0.2)) Text("\(index)") .foregroundStyle(.brown) .background(Color.yellow) } }.frame(height: 200) } } } #Preview("ContentView") { ContentView() } extension Binding { @MainActor func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> { Binding( get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue handler(newValue) } ) } }
0
0
77
4w
SwiftUI preview for drag/drop APIs
The new drag & drop APIs for macOS 26 are terrific, but there's an important missing piece. If I use draggable(containerItemID:), there's no way to provide a custom view for the drag image. Meanwhile the older API lets you provide a preview, but you miss out on things like multi-item drag and custom drag sessions. Is there some mechanism for supplying a preview that I'm not seeing? Without it, the drag interface in my apps is going to look terrible.
0
0
72
Aug ’25
iOS 26 navigationTransition .zoom issue
When I dismiss a view presented with .navigationTransition(.zoom), the source view gets a weird background (black or white depending on the appearance) for a couple of seconds, and then it disappears. Here’s a simple code example. import SwiftUI struct NavigationTransition: View { @Namespace private var namespace @State private var isSecondViewPresented = false var body: some View { NavigationStack { ZStack { DetailView(namespace: namespace) .onTapGesture { isSecondViewPresented = true } } .fullScreenCover(isPresented: $isSecondViewPresented) { SecondView() .navigationTransition(.zoom(sourceID: "world", in: namespace)) } } } } struct DetailView: View { var namespace: Namespace.ID var body: some View { ZStack { Color.blue Text("Hello World!") .foregroundStyle(.white) .matchedTransitionSource(id: "world", in: namespace) } .ignoresSafeArea() } } struct SecondView: View { var body: some View { ZStack { Color.green Image(systemName: "globe") .foregroundStyle(Color.red) } .ignoresSafeArea() } } #Preview { NavigationTransition() }
2
4
112
3d
Question about the Scope and "Inheritance" Behavior of SwiftUI Modifiers
I am confused about the "inheritance" behavior of modifiers in SwiftUI. Some modifiers (such as .background, .clipShape, etc.) seem to affect both parent and child views inconsistently. Here are some specific examples I encountered in Xcode 16.4 with the iOS 18.5 iPhone 16 Pro simulator: struct ContentView: View { var body: some View { VStack { // RedVStack Text("Hello world!") VStack { // OrangeVStack Text("Hello") Text("Hello") } .background(.orange) } .background(.red, in: RoundedRectangle(cornerRadius: 5)) // RedVStack has rounded corners, OrangeVStack also has rounded corners } } struct ContentView: View { var body: some View { VStack { // RedVStack Text("Hello world!") VStack { // OrangeVStack Text("Hello") Text("Hello") } .background(.orange) Text("Hello world!") } .background(.red, in: RoundedRectangle(cornerRadius: 5)) // RedVStack has rounded corners, OrangeVStack does not have rounded corners } } struct ContentView: View { var body: some View { VStack { // RedVStack Text("Hello world!") VStack { // OrangeVStack Text("Hello") Text("Hello") } .background(.orange) } .background(.red) .clipShape(RoundedRectangle(cornerRadius: 5)) // RedVStack has rounded corners, OrangeVStack does not have rounded corners } } I find it difficult to understand which modifiers affect child views and which do not. Is there any official documentation or authoritative explanation that can help me understand the scope and "inheritance" mechanism of SwiftUI modifiers? Thank you!
0
0
54
Aug ’25
Popover in Toolbar Causes Crash in Catalyst App on macOS 26
Hi everyone, I’ve encountered an issue where using a popover inside the toolbar of a Catalyst app causes a crash on macOS 26 beta 5 with Xcode 26 beta 5. Here’s a simplified code snippet: import SwiftUI struct ContentView: View { @State private var isPresentingPopover = false var body: some View { NavigationStack { VStack { } .padding() .toolbar { ToolbarItem { Button(action: { isPresentingPopover.toggle() }) { Image(systemName: "bubble") } .popover(isPresented: $isPresentingPopover) { Text("Hello") .font(.largeTitle) .padding() } } } } } } Steps to reproduce: Create a new iOS app using Xcode 26 beta 5. Enable Mac Catalyst (Match iPad). Add the above code to show a Popover from a toolbar button. Run the app on macOS 26, then click the toolbar button. The app crashes immediately upon clicking the toolbar button. Has anyone else run into this? Any workarounds or suggestions would be appreciated! Thanks!
1
0
55
Aug ’25
Volumetric window not sharing in SharePlay session for VisionOS
I've been struggling with this for far too long so I've decided to finally come here and see if anyone can point me to the documentation that I'm missing. I'm sure it's something so simple but I just can't figure it out. I can SharePlay our test app with my brother (device to device) but when I open a volumetric window, it says "not shared" under it. I assume this will likely fix the video sharing problem we have as well. Everything else works so smooth but SharePlay has just been such a struggle for me. It's the last piece to the puzzle before we can put it on the App Store.
1
0
86
Aug ’25
Dividers not appearing in menu bar on iPadOS 26
On macOS 26 I can see the dividers when I open my Help menu: However, on iPadOS 26 the dividers don't appear: I am simply using Divider() to separate my menu bar items in my CommandGroup. iPadOS does support dividers as I can see them for the system generated Edit menu but for some reason it's not working here. Does anyone know if I am doing something wrong with the iPadOS implementation?
2
1
73
6d