I’m encountering an issue with SwiftUI navigation in iOS 18, where navigating to a DetailView causes unexpected duplication of navigation behavior when @Environment(.dismiss) is used.
Code Example: Here’s a simplified version of the code:
struct ContentView: View {
var body: some View {
NavigationStack {
NavigationLink("Go to Detail View", destination: DetailView())
.padding()
}
}
}
struct DetailView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
let _ = print("DetailView") // This print statement is triggered twice in iOS 18
}
}
}
Issue:
In iOS 18, when @Environment(.dismiss) is used in DetailView, the print("DetailView") statement is triggered twice.
The same code works correctly in iOS 17 and earlier, where the print statement is only triggered once, as expected.
However, when I remove @Environment(.dismiss) from DetailView, the code works as intended in iOS 18, with the print statement being triggered only once and no duplication of navigation behavior.
Alternative Approach with .navigationDestination(for:): I also tested using .navigationDestination(for:) to handle navigation:
struct ContentView: View {
var body: some View {
NavigationStack {
NavigationLink("Go to Detail View", destination: DetailView())
.padding()
}
}
}
struct DetailView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
let _ = print("DetailView") // This print statement is triggered twice in iOS 18
}
}
}
Even with this alternative approach, the issue persists in iOS 18, where the print statement is triggered twice.
What I've Tried:
I’ve confirmed that removing @Environment(.dismiss) solves the issue, and the print statement is triggered only once, and the navigation works as expected in iOS 18 without duplication.
The issue only occurs when @Environment(.dismiss) is in use, which seems to be tied to the navigation stack behavior. The code works correctly in iOS 17 and below, where the print statement is only called once.
Expected Behavior:
I expect the print("DetailView") statement to be called once when navigating to DetailView, and that the navigation happens only once without duplication. The presence of @Environment(.dismiss) should not cause the navigation to be triggered multiple times.
Questions:
Is this a known issue with iOS 18 and SwiftUI navigation? Specifically, is there a new behavior that interacts differently with @Environment(.dismiss)?
Has anyone else encountered this problem, and if so, what’s the recommended way to handle it in iOS 18?
Is there a workaround to ensure that the navigation doesn’t trigger more than once when using @Environment(.dismiss) in iOS 18?
Any help or insights would be greatly appreciated!
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi,
I am working on an agent app.
The app has a menubarextra.
var body: some Scene {
MenuBarExtra(
"menubarextra", systemImage: "star")
{
Button("Item 1") {
}
Button("Item 2") {
}
Button("Item 3") {
}
}
}
I am going to write xctest to click on the icon i created and want to click on the menu next.
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
let menuBarsQuery = XCUIApplication().menuBars
let favouriteStatusItem = menuBarsQuery.statusItems["Favourite"]
favouriteStatusItem.click()
menuBarsQuery.menuItems["Item 1"].click()
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
There is a small problem. When the app is not a agent app, the app will start with with its own menu bar. If i am currently on fullscreen, it will swap to the desktop and the menubar will be showing the app's menu bar. In this case, I can see the menubarextra. The test will pass then.
When it is in agent app, the above behaviour will not happen. Once I run the test with fullscreen mode of xcode, my screen will still stay on xcode and the statusbar will not be showing. Then the test will response
error: -[swiftuitestUITests.MenubarExtraTests testExample] : Element StatusItem, {{1080.0, 6.5}, {34.5, 24.0}}, title: 'Favourite' is not hittable
The only solution I can found at the moment is to leave fullscreen first, then run the test.
In xctest, is there any way to force the statusbar to show first?
Thank you!
Hi I'm new here - I'm trying to learn Swift and SwiftUI.
Tried on PluralSight and Udemy but they have been outdated and thus hard to follow.
So after finding Apples own guides I felt relieved and happy, but now I'm stuck again.
After they've updated Xcode to use #Preview instead of PreviewProvider it's hard to follow along on their tutorial.
Does anyone know of good resources to study SwiftUI? Or know if apple plan to update their tutorials any time soon?
I'm here now if anyone's interested or it's useful information: https://developer.apple.com/tutorials/app-dev-training/managing-state-and-life-cycle
Hello,
I am building an app that records a list view of projects in contentView. I am in Xcode 16.2.
I am having trouble when calling contentView in my @main app file and on the ContentView() line shown in the App file shows that ther is a "Missing argument for parameter 'project' in call". It prompts me to fix it with "Insert', project: ,#Project#.>".
However when I do this like the following:
ContentView(project: Project)
It says "Cannot convert value of type 'Project.Type' to expected argument type 'Project'"
These are my Code below
//Model
import Foundation
import SwiftUI
struct Project: Identifiable {
var name: String
var icon: String
var isFavorite: Bool
var color: Color
let id = UUID()
var compoundscore : Float
static func CurrentProjects() -> [Project] {
return [Project(name: "Test Project", icon: "🍎", isFavorite: true, color: .red, compoundscore: 4.5),
Project(name: "Swimming", icon: "🏊", isFavorite: false, color: .orange, compoundscore: 12.5),
Project(name: "Archery", icon: "🏹", isFavorite: false, color: .yellow, compoundscore: 37.5)
]
}
}
// App view where the error is
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView(project: Project)
}
}
}
// Content View
struct ProjectRow: View {
let project: Project
var body: some View {
HStack {
Text(project.icon)
.font(.title)
Text(project.name)
Spacer()
Image(systemName: project.isFavorite ? "heart.fill" : "heart")
}
}
}
struct ContentView: View {
var CurrentProjectlist = Project.CurrentProjects()
var project: Project
var body: some View {
NavigationView {
List {
Section {
if #available(iOS 17.0, *) {
ForEach(CurrentProjectlist) { project in
ProjectRow(project: project)
}
.listRowBackground(
Capsule()
.fill(Color(project.color))
.padding(.vertical, 2).padding(.horizontal, 20)
)
.listRowSeparator(.hidden)
.foregroundColor(.indigo)
} else {
// Fallback on earlier versions
}
} header: {
Text("CI Projects")
}
.listRowBackground(Color.blue)
.foregroundColor(.black)
.listRowInsets(.init(top: 0, leading: 40, bottom: 0, trailing: 40))
.listRowBackground(Color.black)
.listSectionSeparatorTint(.yellow)
.headerProminence(.increased)
.listRowInsets(EdgeInsets.init(top: 0, leading: 50, bottom: 0, trailing: 50))
}
.scrollContentBackground(.hidden)
.background(
Image("cool background")
.resizable()
.scaledToFill()
.clipped()
.edgesIgnoringSafeArea(.all)
.blur(radius: 3)
.overlay(Color.red.opacity(0.2))
)
.environment(\.defaultMinListHeaderHeight, 20)
.environment(\.defaultMinListRowHeight, 70)
.navigationTitle("Navigator")
}
}
}
Hello!
I have a simple app that opens a sheet and when you press a button on the sheet it will open a quick look preview of a picture. That works great but when I exit the quick look preview it will close the sheet too. This seems like unexpected behavior because it doesn't happen on iOS.
Any help is appreciated, thank you.
Here is some simple repo:
import QuickLook
import SwiftUI
struct ContentView: View {
@State private var pictureURL: URL?
@State private var openSheet = false
var body: some View {
Button("Open Sheet") {
openSheet = true
}
.sheet(isPresented: $openSheet) {
Button("Open Picture") {
pictureURL = URL(fileURLWithPath: "someImagePath")
}
// When quick look closes it will close the sheet too.
.quickLookPreview($pictureURL)
}
}
}
And here is a quick video:
I have a map where I am using UserAnnotation() to show the user's location.
Location permissions are handled elsewhere in the app.
If the user has previously granted location permission, that is enough for the UserAnnotation() blue pin to appear. Otherwise, it just doesn't draw.
So the Map already knows the user's permission and location without my code again requesting location etc.
I was looking for a way to leverage the map's knowledge of the user's location and came across this struct as described in the Documentation for SwiftUI Mapkit
public struct UserLocation {
public var heading: CLHeading?
public var location: CLLocation?
}
I thought this struct might expose the user's location, but how it is expected to be used or when it should populated is unknown from the point of the documentation.
Would someone please share the purpose and use of this struct?
Hello,
I've been using the @Environment(\.dismiss) var dismiss in a SwiftUI app for the last 2 years which means it was working as expected in iOS 16, iOS 17 and for the most part iOS 18 up until iOS 18.2.1 in which it is causing an endless loop and eventually a crash.
It seems to be something about using a the @Environment(\.dismiss) with a NavigationLink which seems to cause this issue.
When I add a log in my swiftUI views with let _ = Self._printChanges(), I see the following printed out in a loop:
CurrentProjectView: _dismiss changed.
SurveyView: @self changed.
Similar issues have been reported:
https://forums.developer.apple.com/forums/thread/720803
https://forums.developer.apple.com/forums/thread/739512
Any idea how to resolve this ?
In the fileImporter on iOS, when I select a folder, the result is always a subfile belonging to the private folder. This prevents me from accessing these files within the app. However, I do not wish to store them in the sandbox environment. What steps can I take to resolve this issue?
I am building an app playground for SSC'25 where I want to use Multipeer Connectivity framework that would allow me to send and receive data to and from stranger devices. I also want to use some other open-source packages for some of the features. I just wanted to know if we are allowed to use or not?
Topic:
Community
SubTopic:
Swift Student Challenge
Tags:
Swift Student Challenge
Swift Playground
SwiftUI
I intend to participate in the Swift Student Challenge 25. I see Rules, It is mentioned that Playgrounds works should be a work that can be experienced in three minutes. However, my work does not meet this requirement.
Create an interactive scene in an app playground that can be experienced within three minutes.
Initially, my work was not intended for the Challenge but for the App Store. However, I decided to submit it to the Challenge, and my work and I met the requirements of the Challenge. Therefore, my work is a complete application, which makes it impossible for the judges to experience it within three minutes. It may take more time. Does this have any impact?
Topic:
Community
SubTopic:
Swift Student Challenge
Tags:
Swift Student Challenge
Swift
Swift Playground
SwiftUI
When building in Xcode 15.4 debug, only a part of the initial View for List is initialized. As you scroll, new ones are initialized, and old ones are destroyed.
When building the same code in Xcode 16.2, ALL Views are initialized first, and then immediately destroyed as you scroll, new ones are initialized, and old ones are destroyed.
MRE:
struct ContentView: View {
private let arr = Array(1...5555)
var body: some View {
List(arr, id: \.self) {
ListCellView(number: $0)
}
}
}
struct ListCellView: View {
private let number: Int
private let arr: [Int]
@StateObject private var vm: ListCellViewModel // Just to print init/deinit
init(number: Int) {
print(#function, Self.self, number)
self.arr = Array(0...number)
self.number = number
let vm = ListCellViewModel(number: number) // To see duplicates of init
self._vm = StateObject(wrappedValue: vm) // because here is @autoclosure
}
var body: some View {
let _ = print(#function, Self.self, number)
Text("\(number)")
}
}
class ListCellViewModel: ObservableObject {
private let number: Int
init(number: Int) {
print(#function, Self.self, number)
self.number = number
}
deinit {
print(#function, Self.self, number)
}
}
An example from a memory report with this code:
Fortunately, the behavior in release mode is the same as in Xcode 15.4. However, the double initialization of Views is still present and has not been fixed.
...
init(number:) ListCellView 42
init(number:) ListCellViewModel 42
init(number:) ListCellView 42
init(number:) ListCellViewModel 42
deinit ListCellViewModel 42
body ListCellView 42
Yes, unnecessary View initializations and extra body calls are "normal" for SwiftUI, but why do they here twice so that one is discarded immediately?
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.
In my app, User can select word in the UITextView, then I want to insert a content under the selected words(the comment words shouldn't be selected).like:
I found TextKit2 only support edit NSTextParagraph position, or I missed some features in NSTextLayoutManager?
I try to override the NSTextLayoutFragment and update the draw(at point: CGPoint, in context: CGContext) but I found, user still can select the origin content at the origin position, even if the layer of linefragment layer on the corrent position not the origin position.
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.
Hi,
After running the Xcode template "New project > (SwiftUI, SwiftData)" I noticed that there is no insert animation into the list.
The project is a pure vanilla project created from Xcode (Version 16.2 (16C5032a)) and the code is a simple as it gets:
//
// ContentView.swift
//
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
As you see the template's code does have withAnimation inside addItem but there is no animation. The new added item appears without animation in the the List
Here is a short video. Is this a known bug?
Hi,
This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17.
I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this:
struct ManageBooksView: View {
@SectionedFetchRequest<Int16, MyBooks>(
sectionIdentifier: \.groupType,
sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)]
)
private var books: SectionedFetchResults<Int16, MyBooks>
var body: some View {
NavigationStack {
List {
ForEach(books) { section in
Section(header: Text(section.id)) {
ForEach(section) { book in
NavigationLink {
EditView(book: book)
} label: {
Text(book.name)
}
}
}
}
}
.listStyle(.insetGrouped)
}
}
}
struct EditView: View {
private var book: MyBooks
init(book: MyBooks) {
print("Init hit")
self.book = book
}
}
Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again.
Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults.
I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors.
Any suggestions will be helpful, thank you.
I'm developing an app in which I need to render pictures and contain some models in a RealityView. I want to set up a camera, intercept virtual content through the camera, and save it as an image.
Topic:
Spatial Computing
SubTopic:
General
Tags:
SwiftUI
RealityKit
Reality Composer Pro
Shader Graph Editor
I have a swiftui view with Button(intent: ) and using UIHostingViewcontroller to use it in UIKit. The problem is that button not works in uikit but normal button(without intent works)
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough:
moc.delete(thing)
try? moc.save()
Here is my DataController. I'm happy to provide more info as needed
class DataController: ObservableObject {
let container: NSPersistentCloudKitContainer
@Published var moc: NSManagedObjectContext
init() {
container = NSPersistentCloudKitContainer(name: "AppName")
container.loadPersistentStores { description, error in
if let error = error {
print("Core Data failed to load: \(error.localizedDescription)")
}
}
#if DEBUG
do {
try container.initializeCloudKitSchema(options: [])
} catch {
print("Error initializing CloudKit schema: \(error.localizedDescription)")
}
#endif
moc = container.viewContext
}
}
The Problem
I am trying to implement a pinch-to-zoom feature on images within a UIPageViewController. However, often times when trying to pinch to zoom, the magnification gesture gets overridden by the scrolling gesture built into the UIPageViewController. I'm not sure how to get around this. The Apple Photos app seems to allow pinch to zoom on photos inside a full-page scrolling view without any issue, so I believe it should be possible.
Versions: iOS 17.2.1 - iOS 18.2.1, Swift (SwiftUI), Xcode 15.1
Steps to Reproduce
Run this sample Xcode project on a physical device: https://drive.google.com/file/d/1tB1QyY6QPEp-WLzdHxgDdkM45xCAELLr/view?usp=share_link
Try pinching to zoom on the image. After a few goes at it, you'll likely find that one time it will scroll instead of pinching to zoom. It might take up to a dozen pinches to experience this issue.
What I've Tried
Making the magnification gesture a high priority gesture.
Having only one page in the paging view controller.
Subclassing UIScrollView and conforming to the UIGestureRecognizerDelegate in that subclass, as explained here: https://stackoverflow.com/a/51070947/12218938
Using the iOS 17 ScrollView instead. Unfortunately it has the same issue but even worse! It's possible that since this is a native SwiftUI view, people might have solutions to this, but from a brief search I couldn't find any.
If you set the data source to nil (which indicates that there are no other pages for the paging view controller to scroll to), it does work, but it's not a workable solution since the time you'd want to set the data source to nil is when the user pinches the screen, but you can't know when the user pinches the screen if the gesture doesn't work!
Other Ideas/Workarounds
We could have some "zoom" mode that temporarily cancels the ability to scroll while zooming. But this seems like not too nice/intuitive of a solution.
If there is no paging view that Apple provides which could be made compatible with a pinch-to-zoom gesture, it's possible we would have to make a completely custom paging view. But that would be a lot of work I presume, so it's probably not something we would have time for right now.