While using Screen Mirroring in developer mode within my immersive space, I noticed an alignment issue with the computer cursor (transparent circle). When I move it toward an attachment view, the cursor remains horizontal instead of aligning with the surface of the attachment view. It shows correctly on a 2D window only wrong on attachment view.
Is this behavior a bug, or could it be caused by a missing or incorrect configuration on the attachment view?
Want help, thanks.
SwiftUI
RSS for tagProvide 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
Goal : Drag a sphere across the room and track it's position
Problem: The gesture seems to have no effect on the sphere ModelEntity. I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you
import SwiftUI
import RealityKit
import RealityKitContent
import Foundation
@main
struct testApp: App {
@State var immersionStyle:ImmersionStyle = .mixed
var body: some Scene {
ImmersiveSpace {
ContentView()
}
.immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive)
}
}
struct ContentView: View {
@State private var lastPosition: SIMD3<Float>? = nil
@State var subscription: EventSubscription?
@State private var isDragging: Bool = false
var sphere: ModelEntity {
let mesh = MeshResource.generateSphere(radius: 0.05)
let material = SimpleMaterial(color: .blue, isMetallic: false)
let entity = ModelEntity(mesh: mesh, materials: [material])
entity.generateCollisionShapes(recursive: true)
return entity
}
var drag: some Gesture {
DragGesture()
.targetedToEntity(sphere)
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
Text("Hello, World!")
RealityView { content in
//1. Anchor Entity
let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1))
let ball = sphere
//1.2 add component to ball
ball.components.set(InputTargetComponent())
//2. add anchor to sphere
anchor.addChild(ball)
content.add(anchor)
subscription = content.subscribe(to: SceneEvents.Update.self) { event in
let currentPosition = ball.position(relativeTo: nil)
if let last = lastPosition, last != currentPosition {
print("Sphere moved from \(last) to \(currentPosition)")
}
lastPosition = currentPosition
}
}
.gesture(drag)
}
}
I am developing an application which make use of 2 ornaments anchored to a volumetric window, one used a toolbar and one to display different views.
The problem I am facing consistently is that the ornaments seems to scale up or down after moving the volume using the OS handle or starting a GroupActivity session.
This first image shows the ornaments as soon as I started the app, no dragging nor group activities:
This second images shows them as soon as I join a group activity session:
The map, which might seem smaller, has not been touched and has always the same scale.
In this last image I had just dragged the entire volume using the OS toolbar, resulting in the ornaments scaling down:
This is how the volume and the ornaments are declared:
WindowGroup(id: "CityVolume") {
let cityVM = CityViewModel(volumeSize: CityView.initialVolumeSize)
CityView(cityVM: cityVM)
.ornament(attachmentAnchor: .scene(.bottomFront)) {
HStack {
TourismChartsButton()
LandmarksListButton()
CenterMapButton()
ToggleImmersiveSpaceButton()
TrafficDataButton()
BusLinesButton()
}
.padding()
.offset(z: 10)
.rotation3DEffect(Angle(degrees: 15), axis: (x: 1.0, y: 0.0, z: 0.0))
}
.ornament(attachmentAnchor: .scene(.back)) {
ZStack {
if AppModel.Instance.tourismVM.isChartViewVisible {
TourismChartsView()
}
if AppModel.Instance.busLinesVM.isDataViewEnabled {
BusLineView()
}
}
}
.task(observeGroupActivity)
.onAppear {
appModel.cityVM = cityVM
}
}
.windowStyle(.volumetric)
.windowResizability(.contentSize)
.volumeWorldAlignment(.gravityAligned)
.defaultSize(CityView.initialVolumeSize, in: .meters)
It happens also without starting a SharePlay session, but not as frequently as during SharePlay. Experienced the same behaviour with toolbars.
Am I doing something wrong with how I created the ornaments? Am I missing something?
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now.
The FoodTruckModel adds new Order values with an animation:
// FoodTruckModel.swift
withAnimation(.spring(response: 0.4, dampingFraction: 1)) {
self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator))
}
This then animates the OrdersTable when new Order values are added.
Here is a small change to OrdersTable:
// OrdersTable.swift
- @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)]
+ @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)]
Running the app now inserts new Order values at the top.
The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top:
What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation.
Scrolling the Table fixes the animation.
Changing the creationData sort order from reverse to forward and back to reverse fixes the animation.
Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
We recently migrated our app to use NavigationSplitView on iPad with a sidebar and detail setup, and we got reports that the navigation buttons on the sidebar disappear when returning to our app after using a different app. I reproduced the issue from a new empty project with the following code (issue tested on iOS 17.4 and iOS 18.3, was not able to reproduce on iOS 16.4):
import SwiftUI
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
NavigationSplitView {
Text("sidebar")
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(action: {}) {
Image(systemName: "square.and.arrow.down")
}
}
ToolbarItem(placement: .topBarTrailing) {
Button(action: {}) {
Image(systemName: "square.and.arrow.up")
}
}
}
} detail: {
Text("detail")
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(action: {}) {
Image(systemName: "eraser")
}
}
ToolbarItem(placement: .topBarTrailing) {
Button(action: {}) {
Image(systemName: "pencil")
}
}
}
}
}
}
}
Please check the following GIF for the simple steps, notice how the navbar buttons in the detail view do not disappear:
Here's the console output, it shows that the constraints break internally:
I have a TextField and entered for example "sg?!". At the TextField I set the modifier speechAlwaysIncludesPunctuation(). But when I activate VoiceOver the content of TextField is reading. The special characters don't read out.
How can I fix this?
As the title says, I am not sure how to properly build an inverted ScrollView where I can safely insert items above my data ("prepend") without everything jumping around.
My current code is essentially this:
@State private var scrollPosition = ScrollPosition(idType: Message.ID.self)
private func onMessageDidScrollIntoView(_ id: Message.ID) {
let indexOfVisibleMessage = /* ... */
if indexOfVisibleMessage < 10 {
fetchOlderMessages()
// ^ this updates my ViewModel `messages`
}
}
var body: some View {
ScrollView {
LazyVStack {
ForEach(messages) { message in
MessageCell(message)
}
}.scrollTargetLayout()
}
.defaultScrollAnchor(.bottom)
.scrollPosition($scrollPosition)
.onChange(of: scrollPosition) { oldValue, newValue in
guard let visibleMessageId = scrollPosition.viewID(type: Message.ID.self) else { return }
onMessageDidScrollIntoView(visibleMessageId)
}
}
..so if the user scrolls up to the oldest 10 messages, I start loading more and insert them at the top.
The problem with this is that the ScrollView now jumps when new messages are inserted. This is because the ScrollView maintains it's Y position, but the content size changes since we are adding new items "above".
I tried to play around with a few suggestions I found on StackOverflow, namely;
Inverting the ScrollView (.scaleEffect(y: -1) on the ScrollView and then again on the MessageCell to counter it): This somehow jumped the x position of the ScrollView and completely breaks .contextMenu.
Playing around with .onScrollGeometryChange to update scrollPosition.scrollTo(y:) when it's contentSize changes: This just didn't work and stopped the user scroll gesture/interaction.
Setting scrollPosition to the Message.ID I want to keep stable before doing an update: This didn't do anything.
But nothing actually worked for the reasons described above.
How do you actually build these UIs in SwiftUI? I think an inverted ScrollView is quite a common UI, and obviously data has to be loaded lazily.
After updating to Xcode 16.3, getting the error - Symbol not found: ___cxa_current_primary_exception
It didn't happen with Xcode 16.2 that I used before, but after updating to 16.3, when I build the app, the following error is output to the console and the app doesn't run.
dyld[2150]: Symbol not found: ___cxa_current_primary_exception
Referenced from: <6B00A4F2-B208-3FDB-BA38-B7095AF0034A> /private/var/containers/Bundle/Application/B590DB18-9C66-4C9E-8330-104943419E60/Mubeat DEV.app/Mubeat DEV.debug.dylib
Expected in: <7F51CB08-A0CA-386E-BB62-4B8BFB0CED9F> /usr/lib/libc++.1.dylib
Symbol not found: ___cxa_current_primary_exception
Referenced from: <6B00A4F2-B208-3FDB-BA38-B7095AF0034A> /private/var/containers/Bundle/Application/B590DB18-9C66-4C9E-8330-104943419E60/Mubeat DEV.app/Mubeat DEV.debug.dylib
Expected in: <7F51CB08-A0CA-386E-BB62-4B8BFB0CED9F> /usr/lib/libc++.1.dylib
dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
After looking for another solution, I found a way to remove the -Objc option in Other Linker Flags, but this method only works on iOS 18.4 and doesn't work on other versions.
Is there another solution?
Hi everyone,
I’m using a custom TipViewStyle to modify the background and slightly adjust the layout of the Tips in my app. Everything looked great until iOS 18.4. Since updating, the layout is being compressed, and the message inside the Tip is getting truncated.
Here’s a screenshot of how it looks on iOS 18.4 (truncated message)
and another showing how it used to look before iOS 18.4 (correct layout).
Here is the relevant code for the custom style:
struct CustomTipViewStyle: TipViewStyle {
func makeBody(configuration: Configuration) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
configuration.title?
.font(.headline)
.foregroundColor(.daBackground)
Spacer()
Button(action: { configuration.tip.invalidate(reason: .tipClosed) }) {
Image(systemName: "xmark")
.foregroundColor(.daBackground.opacity(0.3))
}
}
VStack(alignment: .leading, spacing: 8.0) {
configuration.message?
.font(.subheadline)
.foregroundColor(.daBackground.opacity(0.8))
Divider().background(.daBackground.opacity(0.3))
ForEach(configuration.actions) { action in
HStack {
Spacer()
Button(action: action.handler) {
action.label()
.foregroundStyle(.accent)
.font(.system(size: 18, weight: .bold))
}
}
}
}
}
.padding()
.background(Color.daBlack)
}
}
Has anyone else experienced this issue with TipViewStyle in iOS 18.4? Any workarounds or solutions would be appreciated!
Thanks in advance!
Goal : Drag a sphere across the room and track it's position
Problem: The gesture seems to have no effect on the sphere ModelEntity.
I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you
import SwiftUI
import Foundation
import UIKit
@main
struct testApp: App {
@State var immersionStyle:ImmersionStyle = .mixed
var body: some Scene {
ImmersiveSpace {
ContentView()
}
.immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive)
}
}
struct ContentView: View {
@State private var lastPosition: SIMD3? = nil
@State var subscription: EventSubscription?
@State private var isDragging: Bool = false
var sphere: ModelEntity {
let mesh = MeshResource.generateSphere(radius: 0.05)
let material = SimpleMaterial(color: .blue, isMetallic: false)
let entity = ModelEntity(mesh: mesh, materials: [material])
entity.generateCollisionShapes(recursive: true)
return entity
}
var drag: some Gesture {
DragGesture()
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
RealityView { content in
//1. Anchor Entity
let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1))
let ball = sphere
//2. add anchor to sphere
anchor.addChild(ball)
content.add(anchor)
subscription = content.subscribe(to: SceneEvents.Update.self) { event in
let currentPosition = ball.position(relativeTo: nil)
if let last = lastPosition, last != currentPosition {
print("Sphere moved from \(last) to \(currentPosition)")
}
lastPosition = currentPosition
}
}
.gesture(drag)
}
}
I use swiftui to build apps on iPhone and iPad.
There is no problem with the iPhone app.
The game display is fully shown on iPhone.
However, for the iPad, the game display is not shown and the screen goes black.
I had to tap the button on the upper left side.(looks like a side view button)
After that, the game display is only shown in the left side in a very small size.
How can I make the game display fully shown in the iPad?
Hi,
In mac os swift ui application when i set window.isReleasedWhenClosed and when i close the window the app is getting crashed with exc_bad_access. but when i leave it to default value the app is not crashing. for some windows setting window.isReleasedWhenClosed to true is woking properly when closing the windows. But for some windows it is crashing. If i dont set it to true the window is not removed from NSApplication.shared.windows sometimes. I am confused about setting isReleasedWhenClosed to true
Could someone calrify on this please.
thank in advance.
When presenting a SwiftUI sheet containing ObservableObject's injected using environmentObject(_) modifier, the objects are unexpectedly retained after the sheet is dismissed if a TextField within the sheet gains focus or is edited.
This issue occurs on iOS and iPadOS (on macOS the objects are always released), observable both in the simulator and on physical devices, and happens even when the view does not explicitly reference these environment objects, and the TextField's content isn't bound to them.
Expected Results:
When the sheet is dismissed, all environment objects passed to the sheet’s content view should be released (deinitialized), regardless of whether the TextField was focused or edited.
Actual Results:
If the TextField was focused or edited, environment objects (ObservableA and ObservableB) are retained after the sheet is dismissed. They are not deinitialized as expected, leading to unintended retention.
Interestingly, previously retained copies of these environment objects, if any, are released precisely at the moment the TextField becomes focused on subsequent presentations, indicating an inconsistent lifecycle behavior.
I have filed an issue FB17226970
Sample Code
Below is a sample code that consistently shows the issue on iOS 18.3+.
Steps to Reproduce:
Run the attached SwiftUI sample.
Tap the button labeled “Show Sheet” to present a sheet.
Tap on the TextField to focus or begin editing.
Dismiss the sheet by dragging it down or by other dismissal methods (e.g., tapping outside on iPadOS).
import SwiftUI
struct ContentView: View {
@State private var showSheet: Bool = false
var body: some View {
VStack {
Button("Show Sheet") {
showSheet = true
}
}
.sheet(isPresented: $showSheet) {
SheetContentView()
.environmentObject(ObservableA())
.environmentObject(ObservableB())
}
}
}
struct SheetContentView: View {
@State private var text: String = ""
var body: some View {
TextField("Select to retain observable objects", text: $text)
.textFieldStyle(.roundedBorder)
}
}
final class ObservableA: ObservableObject {
init() {
print(type(of: self), #function)
}
deinit {
print(type(of: self), #function)
}
}
final class ObservableB: ObservableObject {
init() {
print(type(of: self), #function)
}
deinit {
print(type(of: self), #function)
}
}
#Preview {
ContentView()
}
I'm developing a medication scheduling app similar to Apple Health's Medications feature, and I'd like some input on my current approach to background tasks.
In my app, when a user creates a medication, I generate ScheduledDose objects (with corresponding local notifications) for the next 2 weeks and save them to SwiftData. To ensure this 2-week window stays current, I've implemented a BGAppRefreshTask that runs daily to generate new doses as needed.
My concern is whether BGAppRefreshTask is the appropriate mechanism for this purpose. Since I'm not making any network requests but rather generating and storing local data, I'm questioning if this is the right approach.
I'm also wondering how Apple Health's Medications feature handles this kind of scheduling. Their app seems to maintain future doses regardless of app usage patterns.
Has anyone implemented something similar or can suggest the best background execution API for this type of scenario?
Thanks for any guidance you can provide.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
HealthKit
SwiftUI
Background Tasks
SwiftData
I’m trying to build a CRUD app using SwiftData, @Query model and multidatepicker.
The data from a multidatepicker is stored or persists in SwiftData as Set = [].
My current dilemma is how to use SwiftData and @Query model Predicate to find all records on the current date.
I can’t find any SwiftData documentation or examples @Query using Set = [].
My CRUD app should retrieve all records for the current date. Unfortunately, I don’t know the correct @Query model syntax for Set = [].
’m experiencing an issue where a Text view is unexpectedly truncated with certain font sizes (e.g., .body) on iOS 17 and later. This does not occur on iOS 16.
I’ve applied .fixedSize(horizontal: false, vertical: true) to allow the text to grow vertically, but it still doesn’t show the entire content. Depending on the text content or font size, it sometimes works, but not always.
How can I ensure the full text is displayed correctly on iOS 17+?
Here is a minimal reproducible SwiftUI example:
let sampleText1 = """
これはサンプルのテキストです、
・箇条書き1
・箇条書き2
であかさたなクロを送り、
アアを『ああああいいいい』フライパンに入れ、あかさたなです😋
"""
let sampleText2 = """
【旬|最高級】北海道産 生サンマ 釜飯
-----
Aaa iii uuu
"""
struct ContentView: View {
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
HStack {
MessageTextView(text: sampleText1)
.layoutPriority(100)
Spacer()
}
HStack {
MessageTextView(text: sampleText2)
.layoutPriority(100)
Spacer()
}
}
}
}
}
struct MessageTextView: View {
var text: String
var body: some View {
Text(text)
.fixedSize(horizontal: false, vertical: true)
.font(.body)
.padding(.leading, 16)
.padding(.trailing, 16)
.padding(.top, 8)
.padding(.bottom, 8)
}
}
img1
img2
We've been receiving crash reports for our app from users that have upgraded to macOS 15.4.
I have upgraded my developer machine and immediately was able to reproduce the crash.
I was able to create a minimal reproducible scenario. The following view crashes the app when sheet is presented with this trace:
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.
<_TtC7SwiftUIP33_7B5508BFB2B0CAF1E28E206F2014E66B23SheetPresentationWindow: 0x1111074c0> 0x9bd (2493) {{0, 0}, {100, 108}} en
(
0 CoreFoundation 0x000000018bdfddf0 __exceptionPreprocess + 176
1 libobjc.A.dylib 0x000000018b8c2b60 objc_exception_throw + 88
2 CoreFoundation 0x000000018bdfdce0 +[NSException exceptionWithName:reason:userInfo:] + 0
3 AppKit 0x000000019043d394 -[NSWindow(NSDisplayCycle) _postWindowNeedsUpdateConstraints] + 1788
4 AppKit 0x000000018f9f8c08 -[NSView _informContainerThatSubviewsNeedUpdateConstraints] + 64
5 AppKit 0x000000018f9f8b8c -[NSView setNeedsUpdateConstraints:] + 468
6 SwiftUI 0x00000001bc0e5110 $s7SwiftUI13NSHostingViewC14setNeedsUpdate33_32B6F54841135BB466A5C1362EB89D05LLyyF + 80
7 SwiftUI 0x00000001bc101f28 $s7SwiftUI13NSHostingViewC13requestUpdate5afterySd_tF + 616
Conditions that are important:
accessing a publishable property inside the sheet
.sheet() on a component that is wrapped in another (VStack is required in the example provided)
being used inside NavigationSplitView
Presents of @Environment(\.openURL. Doesn't have to be used, simply present on the view.
struct ContentView: View {
@Environment(\.openURL) private var open
@State var who = "world"
@State var shown = false
var body: some View {
NavigationSplitView(sidebar: {
Text("Hello, world")
}, detail: {
VStack(spacing: 20) {
Button("Kill me pls") {
shown = true
}
.frame(width: 110, height: 110)
.sheet(isPresented: $shown) {
VStack {
HStack() {
Text("Hello, \(who)!")
}
}
.presentationBackground(.thinMaterial)
}
}
})
}
}
Definitely one of the stranger quirks of SwiftData I've come across.
I have a ScriptView that shows Line entities related to a Production, and a TextEnterScriptView that’s presented in a sheet to input text.
I’m noticing that every time I type in the TextEditor within TextEnterScriptView, a new Line shows up in ScriptView — even though I haven’t explicitly inserted it into the modelContext.
I'm quite confused because even though I’m only assigning a new Line to a local @State array in TextEnterScriptView, every keystroke in the TextEditor causes a duplicate Line to appear in ScriptView.
In other words, Why is SwiftData creating new Line entities every time I type in the TextEditor, even though I’m only assigning to a local @State array and not explicitly inserting them into the modelContext?
Here is my minimal reproducible example:
import SwiftData
import SwiftUI
@main
struct testApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(for: Line.self, isAutosaveEnabled: false)
}
}
}
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@Query(sort: \Production.title) var productions: [Production]
var body: some View {
NavigationStack {
List(productions) { production in
NavigationLink(value: production) {
Text(production.title)
}
}
.navigationDestination(for: Production.self) { production in
ScriptView(production: production)
}
.toolbar {
Button("Add", systemImage: "plus") {
let production = Production(title: "Test \(productions.count + 1)")
modelContext.insert(production)
do {
try modelContext.save()
} catch {
print(error)
}
}
}
.navigationTitle("Productions")
}
}
}
struct ScriptView: View {
@Query private var lines: [Line]
let production: Production
@State private var isShowingSheet: Bool = false
var body: some View {
List {
ForEach(lines) { line in
Text(line.content)
}
}
.toolbar {
Button("Show Sheet") {
isShowingSheet.toggle()
}
}
.sheet(isPresented: $isShowingSheet) {
TextEnterScriptView(production: production)
}
}
}
struct TextEnterScriptView: View {
@Environment(\.dismiss) var dismiss
@State private var text = ""
@State private var lines: [Line] = []
let production: Production
var body: some View {
NavigationStack {
TextEditor(text: $text)
.onChange(of: text, initial: false) {
lines = [Line(content: "test line", production: production)]
}
.toolbar {
Button("Done") {
dismiss()
}
}
}
}
}
@Model
class Production {
@Attribute(.unique) var title: String
@Relationship(deleteRule: .cascade, inverse: \Line.production)
var lines: [Line] = []
init(title: String) {
self.title = title
}
}
@Model
class Line {
var content: String
var production: Production?
init(content: String, production: Production?) {
self.content = content
self.production = production
}
}
I have been trying to implement this look where a component looks "pushed in" but I could not find any resources regarding this effect. The closest I got was a combination of a RoundedRectangle and .glassBackgroundEffect(), but this makes the view look pushed out, instead of pushed in.
I was wondering if this is achievable in SwiftUI level, or even in UIKit level.
Without resorting to NSViewRepresentable, is there a view or view modifier in SwiftUI that can create an NSComboButton on macOS?
NSComboButton was introduced in macOS 13 and is (relatively) new to AppKit:
Apple Developer - NSComboButton
I only require support on macOS for this control.
Note that this is not to be confused with NSComboBox, which is a completely different control.