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

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

Code coverage. SwiftUI Wrong Executable Lines
Hi community: I noticed that each closure is counted as lines in code coverage (unit tests) (Xcode 14.1.0) in a swiftUI File. I mean, If you coded and VStack that involves another HStack, and HStack contains 4 lines, and the VStack contains 6 lines counting the HStack. The total executable lines should be 6 (6 lines in the file). But Xcode count 10, counting twice the HStack lines. Is it a bug, or is it correct? You know, I don't know if Apple has another concept about executable lines. Also, Is it possible to remove previews with any configuration from code coverage or constant files? Thanks for all.
1
2
826
Sep ’25
joblinkapp's registerview mistake
I am working on a SwiftUI project using Core Data. I have an entity called AppleUser in my data model, with the following attributes: id (UUID), name (String), email (String), password (String), and createdAt (Date). All attributes are non-optional. I created the corresponding Core Data class files (AppleUser+CoreDataClass.swift and AppleUser+CoreDataProperties.swift) using Xcode’s automatic generation. I also have a PersistenceController that initializes the NSPersistentContainer with the model name JobLinkModel. When I try to save a new AppleUser object using: let user = AppleUser(context: viewContext) user.id = UUID() user.name = "User1" user.email = "..." user.password = "password1" user.createdAt = Date()【The email is correctly formatted, but it has been replaced with “…” for privacy reasons】 try? viewContext.save() I get the following error in the console:Core Data save failed: Foundation._GenericObjCError.nilError, [:] User snapshot: ["id": ..., "name": "User1", "email": "...", "password": "...", "createdAt": ...] All fields have valid values, and the Core Data model seems correct. I have also tried: • Checking that the model name in NSPersistentContainer(name:) matches the .xcdatamodeld file (JobLinkModel) • Ensuring the AppleUser entity Class, Module, and Codegen are correctly set (Class Definition, Current Product Module) • Deleting duplicate or old AppleUser class files • Cleaning Xcode build folder and deleting the app from the simulator • Using @Environment(.managedObjectContext) for the context Despite all this, I still get _GenericObjCError.nilError when saving a new AppleUser object. I want to understand: 1. Why is Core Data failing to save even though all fields are non-nil and correctly assigned? 2. Could this be caused by some residual old class files, or is there something else in the setup that I am missing? 3. What steps should I take to ensure that Core Data properly recognizes the AppleUser entity and allows saving? Any help or guidance would be greatly appreciated.
3
0
129
Sep ’25
MacOs Tahoe inspector view crash
My app hangs and I get this error when using an inspector view on macos tahoe. Changing to a different type of view resolves the issue. The window has been marked as needing another Update Constraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. <SwiftUI.AppKitWindow: 0x8897e0000> 0xb4d8 (46296) {{1004, 182}, {1254, 948}} en Future marking as needing Update Constraints in Window might be ignored. FAULT: NSGenericException: The window has been marked as needing another Update Constraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. <SwiftUI.AppKitWindow: 0x8897e0000> 0xb4d8 (46296) {{1004, 182}, {1254, 948}} en; (user info absent)
0
1
48
Sep ’25
Empty `safeAreaInset` modifier breaks `Map` zoom region
Reported as FB20357097 In SwiftUI, an empty .safeAreaInset modifier attached to a Map causes the map to become zoomed out to planet level. Minimal reproduction: import SwiftUI import MapKit @main struct map_region_safe_area_inset_bugApp: App { var body: some Scene { WindowGroup { Map { // Any Map content MapCircle(center: .init(latitude: 35.6895, longitude: 139.6917), radius: 1000) } .safeAreaInset(edge: .top) { // No content, `EmptyView()`, `Color.clear` } } } } Note: ZStack { } inside the safeAreaInset prevents the bug. Empty safeAreaInset (bug) Non-empty
0
0
69
Sep ’25
SwiftUI - AsyncImage causing massive tmp folder?
So I have a perplexing situation. I'm loading multiple SwiftUI AsyncImages according to spec (see code below). For some reason, my 1MB app has over 400+ MBs of documents & data. When I view the app's container, I can see that it is caused by a massive number of the images as .tmp files in the "tmp" folder all starting with the name "CFNetworkDownload". It seems that every time an image is loaded, it's stored in here, but does not delete. This makes the app get bigger every time it's opened. What can I do about this issue? Thanks so much! (P.S. I've tried to condense my code down as much as possible for readability, but there's a few files included because I'm not sure where the problem lies.) Main app Swift file: @main struct MyApp: App { let monitor = NWPathMonitor() @State private var isConnected = true var body: some Scene { monitor.pathUpdateHandler = { path in if path.status == .satisfied { if !isConnected { isConnected.toggle() } } else { if isConnected { isConnected.toggle() } } } let queue = DispatchQueue(label: "Monitor") monitor.start(queue: queue) return WindowGroup { isConnected ? AnyView(ContentView()) : AnyView(ContentViewFailed()) } } } The ContentView that's loaded inside the above WindowGroup: struct ContentView: View { var body: some View { TabView { HomeView() .tabItem { Image(systemName: "house.fill") Text("Home") } . . . } } } And finally, the HomeView where the images are being loaded: struct HomeView: View { var body: some View { let urlString = "https://www.example.com/Home.json" if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { do { items = try JSONDecoder().decode([Item].self, from: data) } catch { print(error) } } } return NavigationView { List { ScrollView { VStack(alignment: .leading) { ZStack { VStack(alignment: .leading) { Spacer() HStack { AsyncImage(url: URL(string: "https://www.example.com/images/example.png")) { image in image .resizable() .aspectRatio(contentMode: .fill) .shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.25), radius: 1) } placeholder: { ProgressView() .progressViewStyle(.circular) } .frame(width: 202, height: 100) } . . . } } } } } } } } I really appreciate your time. Not sure if this could just be a bug with AsyncImage itself.
2
1
1.5k
Sep ’25
iOS 26 Beta bug - keyboard toolbar with bottom safe area inset
Hello! I have experienced a weird bug in iOS 26 Beta (8) and previous beta versions. The safe area inset is not correctly aligned with the keyboard toolbar on real devices and simulators. When you focus a new textfield the bottom safe area is correctly placed aligned the keyboard toolbar. On real devices the safe area inset view is covered slightly by the keyboard toolbar, which is even worse than on the simulator. Here's a clip from a simulator: Here's the code that reproduced the bug I experienced in our app. #Preview { NavigationStack { ScrollView { TextField("", text: .constant("")) .padding() .background(Color.secondary) TextField("", text: .constant("")) .padding() .background(Color.green) } .padding() .safeAreaInset(edge: .bottom, content: { Color.red .frame(maxWidth: .infinity) .frame(height: 40) }) .toolbar { ToolbarItem(placement: .keyboard) { Button {} label: { Text("test") } } } } }
2
11
651
Sep ’25
SwiftUI TextField does not update its displayed text when I transform input inside a custom Binding
I’m trying to transform user keyboard input in a TextField so that, for example, whenever the user types the letter "a" it is stored and shown as the Greek letter "α". I created a custom Binding to intercept and modify the typed text before saving it to my observable model. Here’s a simplified version of my code: import SwiftUI class User: ObservableObject { @Published var username: String = "" } struct ContentView: View { @ObservedObject var user = User() var usernameBinding: Binding<String> { Binding( get: { user.username }, set: { newValue in // Replace all "a" with "α" user.username = newValue.replacingOccurrences(of: "a", with: "α") } ) } var body: some View { TextField("Username", text: usernameBinding) .padding() .onChange(of: user.username) { newValue in print("username changed to:", newValue) } } } When I type "a", I can see in the console that the onChange handler prints the transformed string ("α"), and the model (user.username) is updated. However, the TextField on screen still shows the original "a" instead of updating to "α" immediately. I expected the text field to update its displayed value whenever the bound property changes (since username is @Published on an ObservableObject), but that doesn’t seem to happen when I modify the text in the binding’s set closure. Is this a known limitation of SwiftUI TextField? Is there a better way to transform user input so the field shows the transformed text based on some processing? Any advice or explanation would be appreciated.
0
0
72
Sep ’25
RealityView doesn't free up memory after disappearing
Basically, take just the Xcode 26 AR App template, where we put the ContentView as the detail end of a NavigationStack. Opening app, the app uses < 20MB of memory. Tapping on Open AR the memory usage goes up to ~700MB for the AR Scene. Tapping back, the memory stays up at ~700MB. Checking with Debug memory graph I can still see all the RealityKit classes in the memory, like ARView, ARRenderView, ARSessionManager. Here's the sample app to illustrate the issue. PS: To keep memory pressure on the system low, there should be a way of freeing all the memory the AR uses for apps that only occasionally show AR scenes.
0
0
120
Sep ’25
virtual game controller + SwiftUI warning
Hi, I've just moved my SpriteKit-based game from UIView to SwiftUI + SpriteView and I'm getting this mesage Adding 'GCControllerView' as a subview of UIHostingController.view is not supported and may result in a broken view hierarchy. Add your view above UIHostingController.view in a common superview or insert it into your SwiftUI content in a UIViewRepresentable instead. Here's how I'm doing this struct ContentView: View { @State var alreadyStarted = false let initialScene = GKScene(fileNamed: "StartScene")!.rootNode as! SKScene var body: some View { ZStack { SpriteView(scene: initialScene, transition: .crossFade(withDuration: 1), isPaused: false , preferredFramesPerSecond: 60) .edgesIgnoringSafeArea(.all) .onAppear { if !self.alreadyStarted { self.alreadyStarted.toggle() initialScene.scaleMode = .aspectFit } } VirtualControllerView() .onAppear { let virtualController = BTTSUtilities.shared.makeVirtualController() BTTSSharedData.shared.virtualGameController = virtualController BTTSSharedData.shared.virtualGameController?.connect() } .onDisappear { BTTSSharedData.shared.virtualGameController?.disconnect() } } } } struct VirtualControllerView: UIViewRepresentable { func makeUIView(context: Context) -> UIView { let result = PassthroughView() return result } func updateUIView(_ uiView: UIView, context: Context) { } } class PassthroughView: UIView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { for subview in subviews.reversed() { let convertedPoint = convert(point, to: subview) if let hitView = subview.hitTest(convertedPoint, with: event) { return hitView } } return nil } }
1
0
302
Sep ’25
SwiftUI Picker layout under MacOS26
Prior to MacOS 26, Multiple Pickers could be laid out with a uniform width. For example: struct LayoutExample: View { let fruits = ["apple", "banana", "orange", "kiwi"] let veg = ["carrot", "cauliflower", "peas", "Floccinaucinihilipilification Cucurbitaceae"] @State private var selectedFruit: String = "kiwi" @State private var selectedVeg: String = "carrot" var body: some View { VStack(alignment: .leading) { Picker(selection: $selectedFruit) { ForEach(fruits, id: \.self, content: Text.init) } label: { Text("Fruity choice") .frame(width: 150, alignment: .trailing) } .frame(width: 300) Picker(selection: $selectedVeg) { ForEach(veg, id: \.self, content: Text.init) } label: { Text("Veg") .frame(width: 150, alignment: .trailing) } .frame(width: 300) } } } Renders like this, prior to MacOS26: But now looks like this under MacOS 26: Is there anyway to control the size of the picker selection in MacOS 26?
1
0
78
Sep ’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() }
5
4
276
Sep ’25
Bug Report: SwiftUI @State Array Assignment Fails to Trigger UI Updates. Presumably when lengths of the old and new arrays are the same.
Environment: — Xcode Version: [Current version] — iOS Version: [Target iOS version] — Swift Version: 6.0.3 — Platform: iOS Summary: Direct assignment of new arrays to @State properties sometimes fails to trigger UI updates, even when the arrays contain different data. The assignment appears to succeed in code but the UI continues to display stale data. Presumably when lengths of both arrays are the same. Assigning first empty array and then the new array fixed the issue. Expected Behavior: When assigning a new array to a @State property (self.stateArray = newArray), SwiftUI should detect the change and update the UI to reflect the new data. Actual Behavior: The assignment self.stateArray = newArray executes without error, but the UI continues to display data from the previous array. Debugging shows that self._stateArray (the underlying property wrapper) retains the old data despite the assignment. Minimal Reproduction Case: struct ContentView: View { @State private var items: [String] = ["Old Item"] var body: some View { VStack { ForEach(items, id: \.self) { item in Text(item) } Button("Update Items") { // This assignment may not trigger UI update self.items = ["New Item", "Another Item"] // Workaround: Clear first, then assign // self.items = [] // self.items = ["New Item", "Another Item"] } } } } Workaround: Force the state update by clearing the array before assignment: self.items = [] // Clear first self.items = newArray // Then assign new data Additional Context: — This issue was discovered in a production app where item data loaded from cache wasn't updating the UI. — The same data loading pattern worked in one view (which is modal and doesn't reload data) but failed in another (which needs to be refreshed). — Console logs showed fresh data was loaded but UI displayed stale data. — Debugger showed self._items instead of self.items, which might suggest property wrapper issues. Impact: This causes significant user experience issues where the UI doesn't reflect the actual application state, leading to confusion and apparent data inconsistency. Request: Please investigate why direct @State array assignment sometimes fails and consider fixing the underlying cause, or at minimum document this behavior and recommended workarounds.
1
0
111
Sep ’25
Trouble with contextMenu previewing high resolution images
When using a contextMenu in SwiftUI to show a preview of a PHAsset’s full-size image via PHCachingImageManager.requestImage(), memory usage increases with each image preview interaction. The memory is not released, leading to eventual app crash due to memory exhaustion. The thumbnail loads and behaves as expected, but each call to fetch the full-size image (1000x1000) for the contextMenu preview does not release memory, even after cancelImageRequest() is called and fullSizePreviewImage is set to nil. The issue seems to stem from the contextMenu lifecycle behavior, it triggers .onAppear unexpectedly, and the full-size image is repeatedly fetched without releasing the previously loaded images. The question is, where do I request to the get the full-size image to show it in the context menu preview? STEPS TO REPRODUCE 1/ Create a SwiftUI LazyVGrid displaying many PHAsset thumbnails using PHCachingImageManager. 2/ Add a .contextMenu to each thumbnail button with: .onAppear that triggers requestImage() for a high-resolution preview. .onDisappear that calls cancelImageRequest() and sets the image @State to nil. 3/ Tap on several image previews 4/ Monitor memory usage as it increases and eventually crashes
1
0
115
Sep ’25
RC Pro Timeline Notification Not Received in Xcode
I'm having a heck of a time getting this to work. I'm trying to add an event notification at the end of a timeline animation to trigger something in code but I'm not receiving the notification from RC Pro. I've watched that Compose Interactive 3D Content video quite a few times now and have tried many different ways. RC Pro has the correct ID names on the notifications. I'm not a programmer at all. Just a lowly 3D artist. Here is my code... import SwiftUI import RealityKit import RealityKitContent extension Notification.Name { static let button1Pressed = Notification.Name("button1pressed") static let button2Pressed = Notification.Name("button2pressed") static let button3Pressed = Notification.Name("button3pressed") } struct MainButtons: View { @State private var transitionToNextSceneForButton1 = false @State private var transitionToNextSceneForButton2 = false @State private var transitionToNextSceneForButton3 = false @Environment(AppModel.self) var appModel @Environment(\.dismissWindow) var dismissWindow // Notification publishers for each button private let button1PressedReceived = NotificationCenter.default.publisher(for: .button1Pressed) private let button2PressedReceived = NotificationCenter.default.publisher(for: .button2Pressed) private let button3PressedReceived = NotificationCenter.default.publisher(for: .button3Pressed) var body: some View { ZStack { RealityView { content in // Load your RC Pro scene that contains the 3D buttons. if let immersiveContentEntity = try? await Entity(named: "MainButtons", in: realityKitContentBundle) { content.add(immersiveContentEntity) } } // Optionally attach a gesture if you want to debug a generic tap: .gesture( TapGesture().targetedToAnyEntity().onEnded { value in print("3D Object tapped") _ = value.entity.applyTapForBehaviors() // Do not post a test notification here—rely on RC Pro timeline events. } ) } .onAppear { dismissWindow(id: "main") // Remove any test notification posting code. } // Listen for distinct button notifications. .onReceive(button1PressedReceived) { (output) in print("Button 1 pressed notification received") transitionToNextSceneForButton1 = true } .onReceive(button2PressedReceived.receive(on: DispatchQueue.main)) { _ in print("Button 2 pressed notification received") transitionToNextSceneForButton2 = true } .onReceive(button3PressedReceived.receive(on: DispatchQueue.main)) { _ in print("Button 3 pressed notification received") transitionToNextSceneForButton3 = true } // Present next scenes for each button as needed. For example, for button 1: .fullScreenCover(isPresented: $transitionToNextSceneForButton1) { FacilityTour() .environment(appModel) } // You can add additional fullScreenCover modifiers for button 2 and 3 transitions. } }
5
0
367
Sep ’25
tabViewBottomAccessory inline functionality missing?
Summary As presented in the SwiftUI WWDC video, the new tabViewBottomAccessory should allow for unique contents for .inline. This is what was presented as being used for the Apple Music miniplayer. However, the functionality seems to be either missing or unintuitive. As seen in the photos attached, not only does .inline functionality not seem to do anything, but the inline accessory also has misaligned elements that cannot be fixed by conditionally modifying the contents. Build Target iOS 26.0 Details This problem recurs on physical devices, simulators, and Xcode previews. Here is a view I've constructed for use as a tabViewBottomAccessory: struct FitnessToolbarAccessory: View { @Environment(\.tabViewBottomAccessoryPlacement) var placement var body: some View { if (placement == .inline) { Text("hello") } else { HStack { HStack { Image(systemName: "dumbbell.fill") VStack(alignment: .leading) { Text("Active Workout") Text("Push Day - Chest") .font(.system(size: 13)) } Spacer() Image(systemName: "pause.fill") } .padding() } } } } Here is the result, working as expected in expanded mode: And here is the result in inline mode after minimizing the tabViewBottomAccessory: The content of this inline accessory is clearly incorrect, as it was specified to contain a Text view containing "hello". Additionally, the contents seem to have some incorrect alignment. This occurs regardless of the contents of the accessory, even plain text.
2
2
202
Sep ’25
Showing space .navigationTitle leads to unexpected results.
I wanted to set navigationTitle value to space symbol on my iOS app (Swift 6, iOS 26.0) (so that navigationBar opens in large mode initially before the actual value is being fetched). In my view I used this: .navigationTitle(" ") And on device I got unexpectedly two quote symbols: Not sure if there is space in between, and the symbols look like opening and closing quote (both quotes in code I think are the same symbols) - so probably it's not part of my code is visible in UI as one might think... . Is this a bug? Or undocumented feature?
0
0
96
Sep ’25
View with FetchRequest doesnt update on change
Hello guys, this is my first post to this forum and really hope that somebody can help me here. I would highly appreciate every help! I am writing my first app with Swift UI (never used UIKit before) which I want to publish later on. This is also my first app which has CoreData implemented. For example I use the following entities: Family, Person 1 Persons can have 1 Family 1 Family can have many Persons My App is structured as the following: ContentView: Contains a TabView with 2 other views in it. A Settings View and a View with a LazyVGrid. LazyVGrid View: This View shows a GridItem for every Family. I get the Families with the following Fetchrequest: @Environment(\.managedObjectContext) private var viewContext // These are the Families from the FetchRequest @FetchRequest(entity: Family.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Family.created, ascending: false)] ) var families: FetchedResults<Family> Every GridItem is linking to a "FamilyDetailView" via NavigationLink. So i pass the family as the following: NavigationLink(destination: FamilyDetailView(family: family).environment(\.managedObjectContext, self.viewContext), label: {Text("Family Name") In the FamilyDetailView i get the Family with a property wrapper: @State var family : Family In this FamilyDetailView is the problem i have. Here I also have a LazyVGrid, which shows 1 NavigationLink for every Person in the Family in a GridItem . In this GridItem I also show for example the "name" of the Person. When tapping the NavigationLink i get to the last View, the PersonDetailView. This View gets the Person which is also an entity which has a relationship to the Family Entity. I pass it as the follow: NavigationLink( destination: PersonDetailView(person: person), label: {Text("Person")}) In the PersonDetailView I now change the name of the person and save the changed to CoreData. The change is saved without a problem, the problem is that when I go back, using the topleading back button from the NavigationView, the Views are not updated. I have to restart the App to see the changes.. I know that the Problem has to be with passing the Data, but I cant figuring out what I did wrong. I really appreciate everyone trying to help me! Thank you very very much!!
1
1
756
Sep ’25
joblinkapp's registerview problem
我正在使用 Core Data 开发一个 SwiftUI 项目。我的数据模型中有一个名为 AppleUser 的实体,具有以下属性:id (UUID)、name (String)、email (String)、password (String) 和 createdAt (Date)。所有属性都是非可选的。 我使用 Xcode 的自动生成创建了相应的 Core Data 类文件(AppleUser+CoreDataClass.swift 和 AppleUser+CoreDataProperties.swift)。我还有一个 PersistenceController,它使用模型名称 JobLinkModel 初始化 NSPersistentContainer。 当我尝试使用以下方法保存新的 AppleUser 对象时: 让用户 = AppleUser(上下文:viewContext) user.id = UUID() user.name = “用户 1” user.email = “...” user.password = “密码 1” user.createdAt = Date()【电子邮件格式正确,但已替换为“...”出于隐私原因】 尝试?viewContext.save() 我在控制台中收到以下错误:核心数据保存失败:Foundation._GenericObjCError.nilError, [:] 用户快照: [“id”: ..., “name”: “User1”, “email”: “...”, “password”: “...”, “createdAt”: ...] 所有字段都有有效值,核心数据模型似乎正确。我还尝试过: • 检查 NSPersistentContainer(name:) 中的模型名称是否与 .xcdatamodeld 文件 (JobLinkModel) 匹配 • 确保正确设置 AppleUser 实体类、模块和 Codegen(类定义、当前产品模块) • 删除重复或旧的 AppleUser 类文件 • 清理 Xcode 构建文件夹并从模拟器中删除应用程序 • 对上下文使用 @Environment(.managedObjectContext) 尽管如此,在保存新的 AppleUser 对象时,我仍然会收到 _GenericObjCError.nilError。 我想了解: 为什么即使所有字段都不是零且正确分配,核心数据也无法保存? 这可能是由于一些残留的旧类文件引起的,还是我缺少设置中的其他内容? 我应该采取哪些步骤来确保 Core Data 正确识别 AppleUser 实体并允许保存? 任何帮助或指导将不胜感激。
2
0
115
Sep ’25