I plan to use the entire screen height minus 40 pixels approximately to not overlap with the time, batter and carrier data. However, I noticed that in the code shared below the vstack with pink background is not displayed at the top of the screen. The interesting part is that it's actually occupying an offset at the top of the screen. What's more, when I set an offset greater than 70 pixels, then the pink vstack displays on the view! Thus, I'm looking for an explanation to this swiftui rendering issue.
Offset less than 70 pixels:
Offset greater or equal than 70 pixels:
GeometryReader { proxy in
let offset = 40.0
let height = proxy.size.height - offset
ZStack {
VStack(spacing:0){
VStack{Text("heasdas")}.frame(width: 300,height: offset,alignment: .leading)
.background(.pink)
VStack {
HStack(alignment:.center,spacing:10){
Text("Shapecloud")
.font(.callout)
.fontWeight(.semibold)
.frame(alignment: .leading)
SLine()
}
.frame(maxWidth: .infinity,alignment: .leading)
Text("Digital Twin Solutions\nServices")
.font(.largeTitle)
.fontWeight(.medium)
.frame(maxWidth: .infinity,alignment: .leading)
}
.frame(maxWidth: .infinity,maxHeight: 0.3*height,alignment: .top)
.background(.red)
VStack {
VideoPlayer(player: player)
.frame(maxWidth: .infinity,maxHeight: 300)
}
.frame(maxWidth: .infinity,maxHeight: 0.4*height)
.background(.yellow)
VStack{
Button {
} label: {
Text("Subscribe now").foregroundStyle(.black)
.font(.headline)
.fontWeight(.semibold)
}
.frame(maxWidth: .infinity,maxHeight: 50)
.border(Color.black, width: 2)
Button {
} label: {
Text("Sign In").foregroundStyle(.white)
.font(.headline)
}
.frame(maxWidth: .infinity,maxHeight: 50)
.background(Color.theme.primary)
}
.frame(maxWidth: .infinity,maxHeight: 0.3*height)
.background(.green)
}
.padding(.horizontal, 32)
.background(.cyan)
.ignoresSafeArea(.all)
}
.ignoresSafeArea(.all)
}
.ignoresSafeArea(.all)
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm struggling to implement a flash animation in SwiftUI.
Generally animations animate from one value to another. I'd like to animate from normal to the flashed state and then back to normal, each time the data shown by the view changes. The "flashed state" could be transparent, or a white background, or it could be a scale change for a pulse effect, or something.
Example:
struct MyView: View
{
let value: String;
var body: some View {
ZStack {
Capsule() .fill(Color.green);
Text(value);
}
};
};
Each time value changes, I'd like the colour of the capsule to quickly animate from green to white and back to green.
I feel this should be easy - am I missing something?
For bonus points:
I'd like the Text to change to its new value at the midpoint of the animation, i.e. when the white text is invisible on the white background.
I'd like to get the flash effect whenever I have a new value even if the new value is equal to the old value, if you see what I mean.
Suppose there are two buttons in VStack, the second button is unclickable. I'm running macOS 15.2 with Xcode 16.2.
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
VStack {
Spacer()
// this button is clickable
Button("foo") {
print("foo")
}
// this button can't be clicked
Button("bar") {
print("bar")
}
}
}
}
}
If I change .horizontal -> .vertical and VStack -> HStack, the second button behave normally.
If I remove ScrollView, everything works fine.
it works fine before macOS 15.2.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi,
I am in need of a solution that takes data from SwiftData classes and generates a PDF with the given data. Any guidance would be greatly appreciated.
Description
I'm developing a tvOS application where I utilize a UISearchController embedded within a UISearchContainerViewController for search functionality. In a particular flow, a custom view controller contains a TVDigitEntryViewController as a child, with its modalPresentationStyle set to .blurOverFullScreen. The issue arises when a user initiates the PIN entry but decides to cancel and return to the search interface without entering a PIN. Upon returning, the search keyboard is no longer visible, and attempts to focus or interact with it are unsuccessful.
Steps to Reproduce
Initialize and present a UISearchContainerViewController that contains a UISearchController with a results view controller.
Within the search results, present a custom view controller containing TVDigitEntryViewController as a child, setting its modalPresentationStyle to .blurOverFullScreen.
Dismiss the custom view controller without entering a PIN (e.g., by pressing the Menu button on the remote).
Observe that upon returning to the search interface, the keyboard is missing, and focus interactions are unresponsive.
Observed Behavior
After dismissing the custom view controller with TVDigitEntryViewController, the search keyboard does not reappear, and the focus system seems to lose track of the search input field.
Expected Behavior
The search keyboard should remain visible and functional after dismissing the custom view controller, allowing users to continue their search without interruption.
Additional Context
I have reviewed the TVDigitEntryViewController documentation (developer.apple.com) and related discussions on the Apple Developer Forums but have not found a solution to this specific issue.
Questions
Has anyone encountered a similar issue or have insights into why the search keyboard becomes unresponsive after dismissing a .blurOverFullScreen modal with a child TVDigitEntryViewController?
Are there recommended practices to ensure the search keyboard remains active and focusable after such modal presentations?
Any guidance or suggestions would be greatly appreciated. Thank you!
I've read all previous posts on this topic but none seem to address what I'm seeing for iOS 16 and using NavigationStack. I'm also using an overall @EnvironmentObject for navigation state.
I have a split view app. In the detail section, I have a NavigationStack surrounding the detail view. Within the detail view (MyView), there is a base view with a "+" button in the toolbar to create a new entity.
That opens NewEntityView where I show a grid of buttons for the user to select a type to create a new entity before moving to NewEntityView to fill in the details for the entity. The top row of the grid of buttons takes the user straight to the NewEntityView with a NavigationLink. These work fine.
The next row of buttons present a menu of sub-types and then should take the user to the NewEntityView view. These buttons do not work.
Code (simplified to not have clutter):
SplitViewDetailView:
struct SplitViewDetailView: View {
@EnvironmentObject var navigationManager: NavigationStateManager
@Binding var selectedCategory: Route?
var body: some View {
NavigationStack(path: $navigationManager.routes) {
// other irrelevant stuff
MyView()
}
.environmentObject(navigationManager)
.navigationDestination(for: Route.self) { $0 }
}
}
MyView:
struct MyView: View {
@EnvironmentObject var navigationManager: NavigationStateManager
var body: some View {
List {
// other stuff
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {}, label: {
NavigationLink(value: Route.newTypeSelect) {
Image(systemName: "plus")
.frame(width: 44, height: 44)
}
} )
}
}
.navigationDestination(for: Route.self) { $0 }
}
SelectTypeView:
struct SelectTypeView: View {
var body: some View {
ZStack {
VStack {
// Top row with no subtypes
HStack {
ForEach (topRows, id: \.self) { type in
NavigationLink(value: Route.newEntityDetails(type.rawValue)) { <-- these work
Text(type)
}
}
}
HStack {
ForEach (middleRow, id: \.self) { type in
Menu {
ForEach (subtype[type], id: \.self) { sub in
NavigationLink(value: Route.newEntityDetails(sub.rawValue)) { <-- these go nowhere
Text(sub)
}
}
} label: {
Text(type)
}
}
}
}
}
}
}
NavigationStateManager:
class NavigationStateManager: ObservableObject {
@Published var routes = [Route]()
// other stuff
}
And Route:
enum Route: Identifiable {
var id: UUID { UUID() }
case newTypeSelect
case newEntityDetails(String)
}
extension Route: View {
var body: some View {
switch self {
case .newTypeSelect:
SelectTypeView()
case .newEntityDetails(let type):
NewEntityView(selectedType: type)
}
}
}
The menus show up fine but tapping on an item does nothing. I've attempted to wrap the menu in its own NavigationStack but that is rejected stating it is already in one defined by a parent view. I've tried making the links Buttons with destinations and those are also rejected.
What is the newest/best way to present a menu with NavigationLinks? One doesn't simply wrap the menu in a NavigationView if one is using a NavigationStack?
Hi,
I'm working on an app that will mostly live in the menu bar.
I'm trying to make a menu item that looks similar to the Tailscale app's menu:
Note: I'm inspired by how Tailscale's menu is rendered:
I have made a View that shows my avatar, name, and optionally the company I work for:
import SwiftUI
struct MenuWhoAmI: View {
var username: String
var binding: String?
var body: some View {
HStack {
AsyncImage(url: URL(string: "https://avatars.githubusercontent.com/u/76716")!){ image in
image.resizable().scaledToFit()
} placeholder: {
ProgressView()
}
.clipShape(Circle())
VStack(alignment: .leading) {
Text(username)
if let binding = binding {
Text("\(binding)").foregroundStyle(.secondary)
}
}
}
}
}
#Preview {
VStack(alignment: .leading) {
MenuWhoAmI(username: "grahamc").padding()
Divider()
MenuWhoAmI(username: "grahamc", binding: "DeterminateSystems").padding()
}.padding()
}
I tried using it in my menu bar:
import SwiftUI
@main
struct DeterminateApp: App {
var body: some Scene {
MenuBarExtra("Determinate", image: "MenuIcon") {
MenuWhoAmI(username: "grahamc")
Button("Two") {}
Button("Three") {}
Divider()
Button("Quit") {
NSApplication.shared.terminate(nil)
}.keyboardShortcut("q")
}.menuBarExtraStyle(.menu)
}
}
and it renders differently:
After reading the forums and documentation, I understood the MenuBarExtra only renders certain elements. I then tried to use an NSStatusBar with an AppDelegate:
import AppKit
import SwiftUI
@main
struct DeterminateApp: App {
@NSApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
Window("Authentication", id: "login") {}
}
}
class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
private var statusItem: NSStatusItem!
func applicationDidFinishLaunching(_ notification: Notification) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem.button {
button.image = NSImage(named: NSImage.Name("MenuIcon"))
}
statusItem.menu = NSHostingMenu(rootView: Group {
Button(action: { print("hi") }) {
MenuWhoAmI(username: "grahamc")
}
})
}
}
and still, the avatar/name doesn't render like I'd expect, missing the circle clipping:
...and I'm a bit mystified.
How can I make this menu render the way I'm trying for?
Thank you!
Using gesture recognizers it is easy to implement a long-press gesture to open a menu, show a preview or something else on the iOS platform. And you can provide the duration the user must hold down the finger until the gesture recognizer fires.
But I could not yet find out how to determine the default duration for a long-press gesture that is configured in the system settings within the "accessibility" settings under "Haptic Touch" (the available options are fast, standard and slow here).
Is it possible to read out this setting, so my App can adapt to this system setting as well?
I have an app which uses Scene
var body: some Scene {
WindowGroup {
RootView(root: appDelegate.root)
.edgesIgnoringSafeArea(.all)
.onOpenURL { url in
let stringUrl = url.absoluteString
if (stringUrl.starts(with: "http")) {
handleUniversalLink(url: stringUrl)
} else if (stringUrl.starts(with: "fb")) {
let _ = ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation])
}
}
}
}
I need to detect when a user taps on status bar. And call some functions when he does it. Is it possible in Swift?
Topic:
UI Frameworks
SubTopic:
SwiftUI
How do I draw a single line of text in a SwiftUI Canvas, scaled to fill a given rectangle?
Example:
Canvas { context, size in
let r = CGRect(origin: CGPointZero, size: size); // Whole canvas
let t = Text("Hello World");
context.draw(t, in: r);
}
Outside of Canvas I'd add .minimumScaleFactor(0) .lineLimit(1), and I guess set a large default font size, and I'd get the result I want.
But inside Canvas, .minimumScaleFactor and .lineLimit don't seem to be available; they return some View, not Text, which can't be used in context.draw. (Is there a trick to make that work?)
I have written the following to do this, but I think there must be an easier way to achieve this! Suggestions?
extension GraphicsContext {
mutating func draw_text_in_rect(string: String, rect: CGRect)
{
let text = Text(string) .font(.system(size: 25));
// The font size used here does matter, because e.g. letter spacing
// varies with the font size.
let resolved = resolve(text);
let text_size = resolved.measure(in: CGSize(width: CGFloat.infinity, height: CGFloat.infinity));
let text_aspect = text_size.width / text_size.height;
let fit_size = CGSize(width: min(rect.size.width, rect.size.height*text_aspect),
height: min(rect.size.height, rect.size.width/text_aspect));
let fit_rect = CGRect(x: rect.origin.x + (rect.size.width-fit_size.width)/2,
y: rect.origin.y + (rect.size.height-fit_size.height)/2,
width: fit_size.width,
height: fit_size.height);
let scale = fit_size.width / text_size.width;
// For debug:
// var p = Path();
// p.addRect(fit_rect);
// stroke(p, with: GraphicsContext.Shading.color(.red), lineWidth: 1);
translateBy(x: fit_rect.minX, y: fit_rect.minY);
scaleBy(x:scale, y:scale);
draw(resolved, at: CGPointZero, anchor: UnitPoint.topLeading);
transform = CGAffineTransformIdentity;
}
};
I'm developing a macOS application and facing an issue with NSTextField delegates after refactoring my code. Here's the situation:
I have an NSWindowController.
Inside the NSWindowController, there's a container NSView named containerView.
On top of containerView, I added a custom NSView subclass named MyDetailsView.
MyDetailsView has two NSTextField instances, and their delegates are properly set. The delegate methods like controlTextDidChange(_:) were getting called as expected.
Due to some additional requirements, I refactored MyDetailsView into MyDetailsViewController, a subclass of NSViewController.
I created a corresponding .xib file for MyDetailsViewController.
Updated the code to load and add MyDetailsViewController's view (view property) to containerView.
Verified that the NSTextField delegates are still being set, and the fields are displayed correctly in the UI.
However, after this refactor, the NSTextField delegate methods (e.g., controlTextDidChange(_:)) are no longer being triggered.
**What I've Tried: **
Verified that the delegates for the NSTextField instances are correctly set after the refactor. Ensured that the MyDetailsViewController's view is added to containerView.
Question: What
could be causing the NSTextField delegate methods to stop working after refactoring from NSView to NSViewController?
@IBOutlet weak var customeView: NSView!
var myDetailsViewController: MyDetailsViewController!
var myDetailsView: MyDetailsView!
var isViewController: Bool = true
override func windowDidLoad() {
super.windowDidLoad()
if isViewController {
myDetailsViewController = MyDetailsViewController(nibName: "MyDetailsViewController", bundle: nil)
self.customeView.addSubview(myDetailsViewController.view)
} else {
myDetailsView = MyDetailsView.createFromNib()
self.customeView.addSubview(myDetailsView!)
}
}
override func showWindow(_ sender: Any?) {
super.showWindow(nil)
window?.makeKeyAndOrderFront(nil)
}
override var windowNibName: NSNib.Name? {
return NSNib.Name("MyWindowController")
}}
class MyDetailsViewController: NSViewController {
@IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
extension MyDetailsViewController: NSTextDelegate {
func controlTextDidChange(_ obj: Notification) {
guard let textField = obj.object as? NSTextField else { return }
print("The value is ----> (MyDetailsViewController) \(textField.stringValue)")
}
}
TextField delegate is set in XIB.
All,
Thanks in advance! I'm having a very hard time increasing the MTU to any value beyond 20. The research I've done states iOS 16.1 and beyond supports up to 512 bytes. Yet, the peripheral device will only read 20 bytes.
It's to be noted that I'm using Expo SDK 51 Bare Workflow, and the react-native-ble-plx library. I have the app functioning as both Central and Peripheral on iOS 18.1 devices, and data is successfully being written and read to the characteristic.
Because the Expo app is Bare Workflow, I'm able to make any configurations via Xcode, and if there is any patches needed to the react-native-ble-plx library, we have the architecture to support that too. I wanted to provide that context before being recommended to go to the Expo forums (which I have/will be).
I also added the CoreBluetooth framework to the project in hopes that would overwrite the react-native-ble-plx imports, but I noticed react-native-ble-plx uses Swift while CoreBluetooth is Objective-C.
Looking forward to your responses!
.onReceive construction isn't working with button long press gesture but tap is working, it increases count by 1. Construction should increase count every 0.5 seconds if button pressed
struct Test: View {
@State private var count = 0
@State private var isLongPressed = false
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increase") {
count += 1
print("Button tapped")
}
.onLongPressGesture {
isLongPressed = true
print("Long press started")
}
.onLongPressGesture(minimumDuration: 0) {
isLongPressed = false
print("Long press ended")
}
}
.onReceive(Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()) { _ in
if isLongPressed {
count += 1
print("Count increased: \(count)")
}
}
}
}
I’m experiencing significant performance and memory management issues in my SwiftUI application when displaying a large number of images using LazyVStack within a ScrollView. The application uses Swift Data to manage and display images.
Here’s the model I’m working with:
@Model
final class Item {
var id: UUID = UUID()
var timestamp: Date = Date.now
var photo: Data = Data()
init(photo: Data = Data(), timestamp: Date = Date.now) {
self.photo = photo
self.timestamp = timestamp
}
}
extension Item: Identifiable {}
The photo property is used to store images. However, when querying Item objects using Swift Data in a SwiftUI ScrollView, the app crashes if there are more than 100 images in the database.
Scrolling down through the LazyVStack loads all images into memory leading to the app crashing when memory usage exceeds the device’s limits.
Here’s my view: A LazyVStack inside a ScrollView displays the images.
struct LazyScrollView: View {
@Environment(\.modelContext) private var modelContext
@State private var isShowingPhotosPicker: Bool = false
@State private var selectedItems: [PhotosPickerItem] = []
@Query private var items: [Item]
var body: some View {
NavigationStack {
ScrollView {
LazyVStack {
ForEach(items) { item in
NavigationLink {
Image(uiImage: UIImage(data: item.photo)!)
.resizable()
.scaledToFit()
} label: {
Image(uiImage: UIImage(data: item.photo)!)
.resizable()
.scaledToFit()
}
}
}
}
.navigationTitle("LazyScrollView")
.photosPicker(isPresented: $isShowingPhotosPicker, selection: $selectedItems, maxSelectionCount: 100, matching: .images)
.onChange(of: selectedItems) {
Task {
for item in selectedItems {
if let data = try await item.loadTransferable(type: Data.self) {
let newItem = Item(photo: data)
modelContext.insert(newItem)
}
}
try? modelContext.save()
selectedItems = []
}
}
}
}
}
Based on this:
How can I prevent SwiftUI from loading all the binary data (photo) into memory when the whole view is scrolled until the last item?
Why does SwiftUI not free memory from the images that are not being displayed?
Any insights or suggestions would be greatly appreciated. Thank you!
I will put the full view code in the comments so anyone can test if needed.
I am working on a SwiftUI project where I need to dynamically update the UI by adding or removing components based on some event. The challenge is handling complex UI structures efficiently while ensuring smooth animations and state management.
Example Scenario:
I have a screen displaying a list of items.
When a user taps an item, additional details (like a subview or expanded section) should appear dynamically.
If the user taps again, the additional content should disappear.
The UI should animate these changes smoothly without causing unnecessary re-renders.
My Current Approach:
I have tried using @State and if conditions to toggle views, like this:
struct ContentView: View {
@State private var showDetails = false
var body: some View {
VStack {
Button("Toggle Details") {
showDetails.toggle()
}
if showDetails {
Text("Additional Information")
.transition(.slide) // Using animation
}
}
.animation(.easeInOut, value: showDetails)
}
}
However, in complex UI scenarios where multiple components need to be shown/hidden dynamically, this approach is not maintainable and could cause performance issues. I need help with the below questions.
Questions:
State Management: Should I use @State, @Binding, or @ObservedObject for handling dynamic UI updates efficiently?
Best Practices: What are the best practices for structuring SwiftUI views to handle dynamic updates without excessive re-renders?
Performance Optimization: How can I prevent unnecessary recomputations when updating only specific UI sections?
Animations & Transitions: What is the best way to apply animations smoothly while toggling visibility of multiple components?
Advanced Approaches: Are there better techniques using @EnvironmentObject, ViewBuilder, or even GeometryReader for dynamically adjusting UI layouts?
Any insights, code examples, or resources would be greatly appreciated.
Hi Team,
We are AAER for Apple and have come across multiple request from customers of BYOD iOS devices that they want to block screenshot and screen sharing for specific work apps like outlook on BYOD iOS devices. Is there any specific App Config Plist for Outlook or .ipa file that will allow us to achieve this.
Hi.
I know to know which window gets hardware keyboard events (such as shortcut key) currently on iPad.
Until iPadOS 15.0, UIApplication.shared.keyWindow, which was deprecated on iPadOS 13.0 and didBecomeKeyNotification/didResignKeyNotification.
But after iPadOS 15.0, a keyWindow is managed by UIScene, not by UIApplication.
Each scene of my app always has just one window.
For my purpose, checking deprecated UIApplication.shared.keyWindow is still effective but didBecomeKeyNotification and didResignKeyNotification don't work because they are fired when a change happens only inside the scene.
So my questions are,
What is the new alternative of UIApplication.shared.keyWindow?
I know a wrong hack like
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first?.windows.filter { $0.isKeyWindow }.first
does not work since the order of connectedScenes is not related with getting hardware keyboard events.
What are the new alternatives of didBecomeKeyNotification/didResignKeyNotification which work on inter-scene?
The second question is more crucial.
Because about the first question, I can still use deprecated UIApplication.shared.keyWindow.
Thanks.
hi does any one know if there changes in lifecycle in xcode 16 ios 18 cause i notice that my view will appear does what view didappear use to do in older version and it kind of a problem cause all the rest of ios work diffrently does anyone else found a problem with it?
or does anyone know if there was a known change to life cycles
Xcode 16.2
Swift 6
macOS Sequoia 15.1
SwiftUI
I am a beginner.
If I understand we can add buttons to the default Menu Bar but not delete them. Am I right? If you do not need most of the buttons, how do you solve that?
I can add a button:
import SwiftUI
@main
struct NouMenuProvesApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.commands {
CommandMenu("Custom") {
Button("Custom Action") {
print("Custom Action performed")
}
}
}
}
}
Can I delete a Menu Button or create a new simpler Menu Bar?
I'm trying to test migration between schemas but I cannot get it to work properly. I've never been able to get a complex migration to work properly unfortunately. I've removed a property and added 2 new ones to one of my data models.
This is my current plan.
enum MigrationV1toV2: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[SchemaV1.self, SchemaV2.self]
}
static let migrateV1toV2 = MigrationStage.custom(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self,
willMigrate: { context in
print("Inside will migrate")
// Get old months
let oldMonths = try context.fetch(FetchDescriptor<SchemaV1.Month>())
print("Number of old months:\(oldMonths.count)")
for oldMonth in oldMonths {
// Convert to new month
let newMonth = Month(name: oldMonth.name, year: oldMonth.year, limit: oldMonth.limit)
print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)")
print("Number of transactions in newMonth: \(newMonth.transactions?.count)")
// Convert transactions
for transaction in oldMonth.transactions ?? [] {
// Set action and direction
let action = getAction(from: transaction)
let direction = getDirection(from: transaction)
// Update category if necessary
var category: TransactionCategory? = nil
if let oldCategory = transaction.category {
category = TransactionCategory(
name: oldCategory.name,
color: SchemaV2.Category.Colors.init(rawValue: oldCategory.color?.rawValue ?? "") ?? .blue,
icon: getCategoryIcon(oldIcon: oldCategory.icon)
)
// Remove old category
context.delete(oldCategory)
}
// Create new
let new = Transaction(
date: transaction.date,
action: action,
direction: direction,
amount: transaction.amount,
note: transaction.note,
category: category,
month: newMonth
)
// Remove old transaction from month
oldMonth.transactions?.removeAll(where: { $0.id == transaction.id })
// Delete transaction from context
context.delete(transaction)
// Add new transaction to new month
newMonth.transactions?.append(new)
}
// Remove old month
context.delete(oldMonth)
print("After looping through transactions and deleting old month")
print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)")
print("Number of transactions in newMonth: \(newMonth.transactions?.count)")
// Insert new month
context.insert(newMonth)
print("Inserted new month into context")
}
// Save
try context.save()
}, didMigrate: { context in
print("In did migrate")
let newMonths = try context.fetch(FetchDescriptor<SchemaV2.Month>())
print("Number of new months after migration: \(newMonths.count)")
}
)
static var stages: [MigrationStage] {
[migrateV1toV2]
}
}
It seems to run fine until it gets the the line: try context.save(). At this point it fails with the following line:
SwiftData/PersistentModel.swift:726: Fatal error: What kind of backing data is this? SwiftData._KKMDBackingData<Monthly.SchemaV1.Transaction>
Anyone know what I can do about this?