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

PDF in WebView
Dear all, Is it possible to replace the default PDF background colour the 50% grey to any other colour while using the new WebView? Using the standard .background method on WebView does not appear to have any effect: WebView(pdfWebpage) .background(Color.blue) // no effect on the background of the PDF Thanks!
1
0
80
Jun ’25
Popover, Menu and Sheet not working with RealityView Attachment SwiftUI
Hi, I have a SwiftUI View, that is attached to a 3D object in Reality View. This is supposed to be a HUD for the user to select a few things. I wanted a sub menu for one of the top level buttons. But looks like none of the reasonable choices like Menu, Sheet or Popover work. Is there a known limitation of RealityKit Views where full SwiftUI cannot be used? Or am I doing something wrong? For example, Button { SLogger.info("Toggled") withAnimation { showHudPositionMenu.toggle() } } label: { HStack { Image(systemName: "rectangle.3.group") Text("My Button") } } .popover(isPresented: $showHudPositionMenu, attachmentAnchor: attachmentAnchor) { HudPositionMenuItems(showHudPositionMenu: $showHudPositionMenu, currentHudPosition: $currentHudPosition) } This will print "Toggled" but will not display the MenuItems Popover. If it makes any difference, this is attached to a child of a head tracked entity.
1
0
73
Jun ’25
For a third year, no screenshot capability for immersive visionOS apps... here's a workaround?
Since only the user can take a screenshot using the Apple Vision Pro's top buttons, the only workaround available to an immersive app that needs a screenshot to document the user's creative interior design choices is ask the user to take a screenshot wait until the user taps a button indicating the screenshot has been taken then the app asks the user to select the screenshot when the app opens the PhotoPicker when the user presses Done, the screenshot is handed off to the app. One wonders why there is no Apple Api for doing this in a simple privacy protective way such as: When called, the Apple api captures the screenshot in Apple secured memory The api displays the screenshot to the user with appropriate privacy warnings and asks if the user wants to a. share this screenshot with the app, or b. cancel, c. retake the screenshot If the user approves, the app receives the screenshot
3
0
64
Jun ’25
interactive glassEffect bug?
Applying glass effect, providing a shape isn't resulting in the provided shape rendering the interaction correctly. .glassEffect(.regular.tint(Color(event.calendar.cgColor)).interactive(), in: .rect(cornerRadius: 20)) results in properly drawn view but interactive part of it is off. light and shimmer appear as a capsule within the rect.
1
8
182
Jun ’25
iOS 26 not showing new screenshot animation
Hi everyone, I’m currently testing iOS 26 on my iPhone as part of the developer program. According to Apple’s documentation and demo materials, a new screenshot animation was introduced in this version. However, when I take a screenshot on my device, the animation remains the same as in previous iOS versions. I’ve double-checked that I’m running the correct build of iOS 26, and I haven’t found any settings that might enable or disable this feature. Is anyone else experiencing the same issue? Could this new animation be device-specific, region-limited, or require additional configuration? Any insight would be appreciated! Thanks in advance, Alonso Rivera
0
0
163
Jun ’25
iOS 26 Reference to member '.glassProminent' cannot be resolved without a contextual typeSourceKit
.glassProminent not working, but .glass works for .buttonStyle() as used here https://youtu.be/3MugGCtm26A?si=dvo2FeE88OnNIwI9&t=938 /Users/brianruiz/repos/taskss/taskss/Views/Components/EmptyStateView.swift:125:39 Reference to member 'glassProminent' cannot be resolved without a contextual type if #available(iOS 26.0, *) { Button(action: { HapticManager.shared.selection() action() }) { Text(buttonLabel ?? "Action") .frame(maxWidth: .infinity) } .padding(.horizontal, 24) .buttonStyle(.glassProminent) .buttonBorderShape(.capsule) .controlSize(.large) .tint(.primary) .offset(y: buttonOffset) .opacity(buttonOpacity) .scaleEffect(isPressed ? 0.95 : 1.0) .animation(.bouncy(), value: isPressed) .onLongPressGesture(minimumDuration: .infinity, maximumDistance: 50, pressing: { pressing in isPressed = pressing }, perform: {}) .onAppear { guard animate else { return } withAnimation(.bouncy().delay(0.6)) { buttonOffset = 0 buttonOpacity = 1 } } } else { // Fallback on earlier versions }
3
1
182
Jun ’25
How to update TabViewBottomAccessoryPlacement
Playing around with the new TabViewBottomAccessoryPlacement API, but can't figure out how to update the value returned by @Environment(\.tabViewBottomAccessoryPlacement) var placement. I want to change this value programmatically, want it to be set to nil or .none on app start until user performs a specific action. (taps play on an item which creates an AVPlayer instance). Documentation I could find: https://developer.apple.com/documentation/SwiftUI/TabViewBottomAccessoryPlacement
4
3
269
6d
iBeacon with CLMonitor Slow
The other day I was playing with iBeacon and found out that CLBeaconIdentityConstraint will be deprecated after iOS 18.5. So I've written code with BeaconIdentityCondition in reference to this Apple's sample project. import Foundation import CoreLocation let monitorName = "BeaconMonitor" @MainActor public class BeaconViewModel: ObservableObject { private let manager: CLLocationManager static let shared = BeaconViewModel() public var monitor: CLMonitor? @Published var UIRows: [String: [CLMonitor.Event]] = [:] init() { self.manager = CLLocationManager() self.manager.requestWhenInUseAuthorization() } func startMonitoringConditions() { Task { print("Set up monitor") monitor = await CLMonitor(monitorName) await monitor!.add(getBeaconIdentityCondition(), identifier: "TestBeacon") for identifier in await monitor!.identifiers { guard let lastEvent = await monitor!.record(for: identifier)?.lastEvent else { continue } UIRows[identifier] = [lastEvent] } for try await event in await monitor!.events { guard let lastEvent = await monitor!.record(for: event.identifier)?.lastEvent else { continue } if event.state == lastEvent.state { continue } UIRows[event.identifier] = [event] UIRows[event.identifier]?.append(lastEvent) } } } func updateRecords() async { UIRows = [:] for identifier in await monitor?.identifiers ?? [] { guard let lastEvent = await monitor!.record(for: identifier)?.lastEvent else { continue } UIRows[identifier] = [lastEvent] } } func getBeaconIdentityCondition() -> CLMonitor.BeaconIdentityCondition { CLMonitor.BeaconIdentityCondition(uuid: UUID(uuidString: "abc")!, major: 123, minor: 789) } } It works except that my sample app can take as long as 90 seconds to see event changes. You would get an instant update with an fashion (CLBeacon and CLBeaconIdentityConstraint). Is there anything that I can do to see changes faster? Thanks.
1
0
58
Jun ’25
Issue with Animations Blocking Taps in UIView Toasts (SwiftUI + Separate UIWindow)
Edit: Well this is embarassing. It looks like I didn't research this thoroughly enough, animations block UIVIew tap events. I found a solution by using DispatchQueue I ran into an unexpected issue when presenting a UIView-based toast inside a separate UIWindow in a SwiftUI app. Specifically, when animations are applied to the toast view (UIToastView), the tap gesture no longer works. To help identify the root cause, I created a minimal reproducible example (MRE) with under 500 lines of code, demonstrating the behavior: Demo GIF: Screen Recording Code Repo: ToastDemo What I Tried: Using a separate UIWindow to present the toast overlay. Adding a tap gesture directly to the UIView. Referencing related solutions: A Blog Post explaining UIWindow usage in SwiftUI - https://www.fivestars.blog/articles/swiftui-windows (Sorry, Apple Dev Forum will not allow a link to this) A Stack Overflow thread on handling touch events in multiple windows. Problem Summary: When animations are involved (fade in, slide up), taps on the toast are not recognized. Without animations, taps work as expected. UIWindow setup seems correct, so I’m wondering if animation effects are interfering with event propagation. I could potentially work around this by restructuring the touch handling, but I'd love insight from the community on why this happens, or if there’s a cleaner fix. Edit: Well this is embarassing. It looks like I didn't research this thoroughly enough, animations block UIVIew tap events. I found a solution by using DispatchQueue
2
0
77
Jun ’25
RealityKit/ARKit Memory Not Fully Released After AR Session Cleanup
Hi, I'm developing a SwiftUI app using RealityKit and ARKit for an AR measuring feature. I’ve noticed that after navigating away from my AR view and performing extensive cleanup (including removing all anchors/entities, pausing the ARSession, and nil-ing out all references), memory usage remains elevated and sometimes grows with repeated AR sessions. Each time I enter and exit the AR view, memory increases The memory does not return to the baseline after cleanup, even though all custom objects are deallocated. Are there best practices beyond what I’ve described to ensure all ARKit/RealityKit resources are released after an AR session?
0
0
69
Jun ’25
Fatal error: Duplicate keys of type 'AnyHashable2' were found in a Dictionary.
I have encountered the following error and reduced my code to the minimum necessary to reliably reproduce this error. Fatal error: Duplicate keys of type 'AnyHashable2' were found in a >Dictionary. This usually means either that the type violates Hashable's >requirements, or that members of such a dictionary were mutated after insertion. It occurs when instances of a swiftdata model are inserted (the error occurs reliably when inserting five or more instances. Fewer insertions seems to make the error either more rare or go away entirely) and a Picker with .menu pickerStyle is present. Any of the following changes prevents the error from occuring: adding id = UUID() to the Item class removing .tag(item) in the picker content using any pickerStyle other than .menu using an observable class instead of a swiftdata class I would greatly appreciate if anyone knows what exactly is going on here. Tested using XCode Version 16.4 (16F6), iPhone 16 Pro iOS 18.5 Simulator and iPhone 15 Pro iOS 18.5 real device. import SwiftUI import SwiftData @Model class Item { var name: String init(name: String) { self.name = name } } struct DuplicateKeysErrorView: View { @Environment(\.modelContext) private var modelContext @Query(sort: \Item.name) private var items: [Item] @State var selection: Item? = nil var body: some View { List { Picker("Picker", selection: $selection) { Text("Nil").tag(nil as Item?) ForEach(items) { item in Text(item.name).tag(item) } } .pickerStyle(.menu) Button("Add 5 items") { modelContext.insert(Item(name: UUID().uuidString)) modelContext.insert(Item(name: UUID().uuidString)) modelContext.insert(Item(name: UUID().uuidString)) modelContext.insert(Item(name: UUID().uuidString)) modelContext.insert(Item(name: UUID().uuidString)) } } .onAppear { try! modelContext.delete(model: Item.self) } } } #Preview { DuplicateKeysErrorView() .modelContainer(for: Item.self) }
1
0
137
Jun ’25
Constraining Beacon with CLBeaconIdentityCondition
In reference to this webpage, I'm turning my iPad to an iBeacon device. class BeaconViewModel: NSObject, ObservableObject, CBPeripheralManagerDelegate { private var peripheralManager: CBPeripheralManager? private var beaconRegion: CLBeaconRegion? private var beaconIdentityConstraint: CLBeaconIdentityConstraint? //private var beaconCondition: CLBeaconIdentityCondition? override init() { super.init() if let uuid = UUID(uuidString: "abc") { beaconIdentityConstraint = CLBeaconIdentityConstraint(uuid: uuid, major: 123, minor: 456) beaconRegion = CLBeaconRegion(beaconIdentityConstraint: beaconIdentityConstraint!, identifier: "com.example.myDeviceRegion") peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) } } func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .poweredOn: startAdvertise() case .poweredOff: peripheralManager?.stopAdvertising() default: break } } func startAdvertise() { guard let beaconRegion = beaconRegion else { return } let peripheralData = beaconRegion.peripheralData(withMeasuredPower: nil) peripheralManager?.startAdvertising(((peripheralData as NSDictionary) as! [String: Any])) } func stopAdvertise() { peripheralManager?.stopAdvertising() } } In Line 10, I'm using CLBeaconidentityConstraint to constrain the beacon. Xcode says that this class is deprecated and suggests that we use CLBeaconIdentityCondition. But if I try to use it, Xcode says Cannot find type 'CLBeaconIdentityCondition' in scope I've just updated Xcode to 16.4. I still get the same error. So how do we use CLBeaconIdentityCondition to constrain the beacon? My macOS version is Sequoia 15.5. Thanks.
2
0
147
Jun ’25
Long press gesture on SwiftUI's Map View (watchOS)
Hi there, I’m developing a watchOS app using SwiftUI, and I want to allow users to interact with the map using the panning gesture and also drop waypoints by long pressing anywhere on the map—just like in the built-in Apple Maps app on watchOS, where a long press drops a pin and panning still works seamlessly. However, with SwiftUI’s Map, any attempt to attach a gesture other than .onTapGesture (such as LongPressGesture or DragGesture) seems to block the built-in map interactions, making panning impossible. Is there a supported approach to detect long press gestures anywhere on the map while still allowing all standard map interactions (as seen in Apple Maps on watchOS)? Or is this something only possible with private APIs or internal access? Any guidance or best practices would be greatly appreciated! Thank you!
1
0
116
Jun ’25
Avoid rotation in a UIViewController with two UIWindow app
Hi, I have an iPhone App with an UIWindowScene and two UIWindow's(mainWindow and alertWindow). In the mainWindow I have the whole app and it is allowed to rotate. The alertWindow is a window to show alert's to the user on the top of the screen and I do not want that the content inside rotate. I thought I may do: override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } And override var shouldAutorotate: Bool { return false } In the rootviewcontroller of alertWindow but after doing those changes the rootviewcontroller of mainWindow does not rotate until I do any navigation. I have thought to have two UIWindowScene's (one per UIWindow) but as far I know iPhone app only supports one UIWindowScene. So, how can I avoid rotation in the viewcontroller of alertWindow without losing the rotation on rootviewcontroller of mainWindow? My viewcontroller is a UIHostingController, so I tried also to avoid from my SwiftUI view but I did not find any solution neither. Thank you in advance
3
0
113
Jun ’25
CGContext PDF/A intents
let dic : [AnyHashable:Any] = [ kCGPDFXRegistryName: "http://www.color.org" as CFString, kCGPDFXOutputConditionIdentifier: "FOGRA43" as CFString, kCGPDFContextOutputIntent: "GTS_PDFX" as CFString, kCGPDFXOutputIntentSubtype: "GTS_PDFX" as CFString, kCGPDFContextCreateLinearizedPDF: "" as CFString, kCGPDFContextCreatePDFA: "" as CFString, kCGPDFContextAuthor: "Placeholder" as CFString, kCGPDFContextCreator: "Placeholder" as CFString ] Hello, Now I would like to export my PDF's as PDF/A. In my opinion, there is also the right option for this under Core Graphics. Unfortunately, the documentation does not show what is 'kCGPDFContextCreatePDFA' or 'kCGPDFContextLinearizedPDF' for a stringvalue is required. What I have already tried: GTS_PDFA1 , PDF/A-1, true as CFString. (Above my CFDictionary. ...Author e.g are working perfectly.) In the Finder you can see these two options, which I would also like to implement in my app. Thank you in advance!
1
0
125
Jun ’25