You'll have to forgive me, I am still pretty new to Swift, but I'm really struggling to figure out what I'm doing wrong or how I can fix it. I'm working on an app that generates an image from some views and then exports that image, but it always returns this very vague error:
The operation couldn’t be completed. (SwiftUI.FileExportOperation.Error error 0.)
Here's most of the program:
import SwiftUI
import UniformTypeIdentifiers
struct ContentView: View {
@State private var backgroundColor = Color.black
@State private var fileExporterIsPresented = false
@State private var image: NSImage?
@State private var fileExporterErrorAlertIsPresented = false
@State private var fileExporterErrorDescription: String?
var body: some View {
let wallpaper = Rectangle()
.foregroundStyle(backgroundColor)
.aspectRatio(16 / 9, contentMode: .fit)
VStack {
wallpaper
.clipShape(.rect(cornerRadius: 10))
.overlay {
RoundedRectangle(cornerRadius: 10)
.strokeBorder(.separator, lineWidth: 5)
}
ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: false)
Button("Generate Wallpaper") {
let renderer = ImageRenderer(content: wallpaper.frame(width: 3840, height: 2160))
image = renderer.nsImage
fileExporterIsPresented = true
}
.fileExporter(
isPresented: $fileExporterIsPresented,
item: image,
contentTypes: [UTType.heic, UTType.png]
) { result in
if case .failure(let error) = result {
fileExporterErrorDescription = error.localizedDescription
fileExporterErrorAlertIsPresented = true
}
}
.alert("File Exporter Failure", isPresented: $fileExporterErrorAlertIsPresented, actions: {
Button("OK") {}
}, message: {
if let fileExporterErrorDescription {
Text(fileExporterErrorDescription)
}
})
.dialogSeverity(.critical)
}
.padding()
}
}
#Preview {
ContentView()
}
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.
Post
Replies
Boosts
Views
Activity
When using the NavigationSplitView with an inspector containing a list which has swipeActions and onDelete, item actions behave erratically.
It seems that there is a gesture conflict between the swipe action and the NavigationSplitView. Is there any modifier that could be used to force gesture focus on the inspector?
struct Animal: Hashable {
var name : String
}
struct ContentView: View {
@State private var isShowingInspector = false
var body: some View {
NavigationSplitView {
Text("Main")
} detail: {
Text("Detail")
.inspector(isPresented: $isShowingInspector) {
InspectorView()
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button {
isShowingInspector.toggle()
} label: {
Label("Preferences", systemImage: "gearshape")
} }
}
}
}
}
}
struct InspectorView: View {
@State var animals = [
Animal(name: "Dog"),
Animal(name: "Cat"),
Animal(name: "Parrot")
]
@State private var selectedAnimal: Animal?
var body: some View {
NavigationStack {
Text(selectedAnimal?.name ?? "Select an animal")
List(selection: $selectedAnimal) {
Section {
ForEach(animals, id: \.self) { animal in
Text(animal.name)
.swipeActions(edge: .leading) {
Button("Edit") {
}
.tint(.green)
}
}
.onDelete { indexSet in
}
} header: {
Text("Animals")
}
}
}
}
}
We are having issues with implementing a List that has Views in it that contain a Textfield.
The criteria we are trying to achieve is
Select to edit the quantity of a product
Auto focus on the row with that textfield, with the textfield's contents selected
Display/Dismiss the keyboard
Mask other rows in the list while interacting with a qty field
We explored many routes and are looking for direction on what the designated approach is. This originally was a Tech Support Incident, and I was instructed to post here. There were 2 working project examples available if needed.
In an implementation that has the FocusState on the parent view, we see collisions in animation / weird jumpiness
// MARK: - Constant
enum Constant {
static let logTag = "AddReplenishmentProductView"
}
@Binding var state: ContentViewState
// MARK: - Private Properties
@State private var focusedLineItemId: String?
// MARK: - Life cycle
var body: some View {
VStack {
replenishmentProductList
}
.background(.tertiary)
.navigationTitle("Add Products")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
}
// MARK: - Private Computed properties
@ViewBuilder
private var replenishmentProductList: some View {
ScrollViewReader { proxy in
List {
let list = Array(state.lineItems.enumerated())
ForEach(list, id: \.1.product.id) { (index, lineItem) in
RowView(
lineItem: $state.lineItems[index],
focusedLineItemId: $focusedLineItemId
)
.id(lineItem.id.uuidString)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.alignmentGuide(.listRowSeparatorLeading) { _ in
return 0
}
// Blocks all the other rows that we are not focusing on.
.maskingOverlay(focusId: $focusedLineItemId, elementId: "\(lineItem.id)")
}
.listSectionSeparator(.hidden)
}
.listStyle(.plain)
.scrollDismissesKeyboard(.never)
.scrollContentBackground(.hidden)
/*
We are looking for a solution that doesn't require us to have this onChange modifier
whenever we want to change a focus.
*/
.onChange(of: focusedLineItemId) {
guard let lineItemId = focusedLineItemId else { return }
/*
We need to scroll to a whole RowView so we can see both done and cancel buttons.
Without this, the focus will auto-scroll only to the text field, due to updating FocusState.
We are experiencing weird jumping issues. It feels like the animations for focus on
text field and RowView are clashing between each other.
To fix this, we added a delay to the scroll so the focus animation completes first and then we
scroll to the RowView.
However, when we attempt to focus on a row that is partially shown, sometimes the RowView won't
update it's focus and won't focus ultimately on the TextField until we scroll.
*/
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation {
// We need to add the withAnimation call to animate the scroll to the whole row.
proxy.scrollTo(lineItemId, anchor: .top)
}
}
}
}
}
}
In an implementation where the FocusState is on the row views, we see issues with actually being able to focus. When quantity field we tap is located on a row near the top/bottom of the screen it does not look to be identified correctly, and the ability to scrollTo / the keyboard being presented are broken.
struct ContentView: View {
// MARK: - Constant
enum Constant {
static let logTag = "AddReplenishmentProductView"
}
@Binding var state: ContentViewState
// MARK: - Private Properties
@State private var focusedLineItemId: String?
@FocusState private var focus: String?
// MARK: - Life cycle
var body: some View {
VStack {
replenishmentProductList
}
.background(.tertiary)
.navigationTitle("Add Products")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
}
// MARK: - Private Computed properties
@ViewBuilder
private var replenishmentProductList: some View {
ScrollViewReader { proxy in
List {
let list = Array(state.lineItems.enumerated())
ForEach(list, id: \.1.product.id) { (index, lineItem) in
RowView(
lineItem: $state.lineItems[index],
focusedLineItemId: $focusedLineItemId,
focus: $focus
)
.id(lineItem.id.uuidString)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.alignmentGuide(.listRowSeparatorLeading) { _ in
return 0
}
// Blocks all the other rows that we are not focusing on.
.maskingOverlay(focusId: $focusedLineItemId, elementId: "\(lineItem.id)")
}
.listSectionSeparator(.hidden)
}
.listStyle(.plain)
.scrollDismissesKeyboard(.never)
.scrollContentBackground(.hidden)
/*
We are looking for a solution that doesn't require us to have this onChange modifier
whenever we want to change a focus.
*/
.onChange(of: focusedLineItemId) {
/*
We need to scroll to a whole RowView so we can see both done and cancel buttons.
Without this, the focus will auto-scroll only to the text field, due to updating FocusState.
However, we are experiencing weird jumping issues. It feels like the animations for focus on
text field and RowView are clashing between each other.
*/
focus = focusedLineItemId
guard let lineItemId = focusedLineItemId else { return }
withAnimation {
// We need to add the withAnimation call to animate the scroll to the whole row.
proxy.scrollTo(lineItemId, anchor: .top)
}
}
}
}
}
Development environment: Xcode 16.1, macOS 15.1 (24B83)
OS version: iOS iOS 17.5 and above
When NavigationStack is presented by a sheet, and navigationDestination API is being used for navigation within the stack, the sheet content is forced to be reevaluated when app is in background.
Sample Project
import SwiftUI
struct TestView: View {
var id: Int
@State private var isLoading = false
@State private var presentSheet = false
var body: some View {
let _ = Self._printChanges()
VStack {
if isLoading {
ProgressView()
} else {
VStack {
Text("View: \(id)")
Text("Not loading")
Button("Present Sheet in NavStack") {
presentSheet = true
}
NavigationLink("Show Link", value: id * 100)
}
}
}
.sheet(
isPresented: $presentSheet,
content: {
NavigationStack {
TestView(id: self.id + 1)
// Comment this block out and note the view no longer reloads when app is in background when there's > 1 sheet modals
.navigationDestination(for: Int.self, destination: { num in
TestView(id: num)
})
}
}
)
.task {
isLoading = true
defer {
isLoading = false
}
try? await Task.sleep(for: .seconds(1))
}
}
}
struct ContentView: View {
var body: some View {
let _ = Self._printChanges()
VStack {
content
.padding()
}
}
var content: some View {
VStack {
NavigationStack {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
TestView(id: 0)
}
.navigationDestination(for: Int.self, destination: { num in
TestView(id: num)
})
}
}
}
}
Steps to reproduce:
To reproduce the issue in the sample project:
Tap on present sheet in navstack button to invoke View #1 presented in sheet
Put the app into multitasking mode by tapping on the simulator home button twice
Observe that console does not emit debug messages on SwiftUI View change. Also observe that there was no loading in the view
Tap on present sheet in navstack button again to invoke View #2 presented in sheet
Repeat step #2, but this time observe that console does emit debug message that SwiftUI View were changed due to the following:
TestView: @self, @identity, _isLoading, _presentSheet changed.
TestView: _isLoading changed.
TestView: _isLoading changed.
To remove the issue:
7. Comment out the block on navigationDestination. Recompile the app and run it in simulator
8. Repeat step 2-5. Note this time the console does not emit debug message that SwiftUI View were changed.
I have a Split View with the sidebar, content, and detail. Everything is working, but when I select on a NavigationLink in my detail view, the back button is seen next to the title above the content view. I want that back button to be displayed in the top bar on the left side of the detail view. I was expecting it to do this automatically, but I must be missing something.
This is where I want it to appear.
This is where it appears.
I made a simplified version of my code, because it would be too much to post but this has the same behavior.
struct TestView: View {
enum SidebarSelections {
case cycles
}
@State private var sidebarSelection: SidebarSelections = .cycles
var body: some View {
NavigationSplitView(sidebar: {
List(selection: $sidebarSelection, content: {
Label("Cycles", systemImage: "calendar")
.tag(SidebarSelections.cycles)
})
}, content: {
switch sidebarSelection {
case .cycles:
NavigationStack {
List {
// Displayed in Content
NavigationLink("Cycle link", destination: {
// Displayed in the Detail
NavigationStack {
List {
NavigationLink("Detail Link", destination: {
Text("More details")
})
}
}
})
}
}
}
}, detail: {
ContentUnavailableView("Nothing to see here", systemImage: "cloud")
})
}
}
Is what I want to do possible? Here is a Stack Overflow post that had it working at one point.
For the last 2 version (18.2 beta 1 and 18.2. beta 2) I haven't been able to successfully update to either of them. I have been running Sequoia on an external drive for testing purposes and didn't have this problem with any of the 18.1 versions.
I'm currently on 18.1 (public) and when I download the update for 18.2 beta 2, the update appears to run (takes about 30 mins), preparing update, the restarts. When the Mac restarts, it just boots straight back to 18.1 without having applied the update.
I am using a Mac Catalyst with SwiftUI for our document-based app with DocumentGroup. The issue is that when we create a new document or open an existing one, the opened view is completely blank. It is only blank/empty when the "Optimzie for Mac" is checked. If it is "Scaled t oMatch iPad", then it works well.
Xcode 16.1
macOS 15.1
struct DocumentGroupTestApp: App {
var body: some Scene {
DocumentGroup(newDocument: WritingAppDocument()) { file in
TestView() // it is empty when it gets opened. It does not work if the option "Optimize for Mac" is checked. If it is scale iPad, then it works.
}
}
}
struct TestView: View {
var body: some View {
Text("Hello, World!")
}
}
I used to be able to display all app icon assets in the UI using UIImage(named: String)
However, it seems this method has been deprecated in Xcode 16 and the iOS 18.
How can I display app icon assets in the UI now, without duplicating the assets?
Hello,
I'm seeing a strange error on another user's device where the SwiftUI file importer doesn't do anything at all. When selecting multiple files and hitting "open", the importer just freezes. Here's a video showing the problem: https://streamable.com/u5grgy
I'm unable to replicate on my own device, so I'm not sure what could be going on. I have startAccessingSecurityScopedResource and stopAccessingSecurityResource everywhere I access a file from fileImporter as well.
I made a LockScreen ControlWidget with CameraCaptureIntent, but I found launch my main app from Control Widget, SceneDelegate will be called like below:
sceneWillEnterForeground
sceneDidBecomeActive
sceneWillResignActive
sceneDidBecomeActive
sceneWillResignActive be called, is it normal?
it make my app camera launch with a delay.
Hi,
In this year WWDC 2024 conference a new update to SwiftData allows it to connect to other kind of data sources or databases, at ;east this is what I understood, since then didn't see any tutorial or help document on how to do that for example connecting SwiftData to Firebase if possible ?
Kind Regards
Hi
When connecting a SwiftData module property to a SwiftUI view such as a text field and the field changes by user the property get updated in the SwiftData database, now suppose I want to run a validation code or delay updates to Database till use click a submit button how to do that ? delay those auto updates if we can name it ?
Kind Regards
Code Example
import SwiftUI
import SwiftData
struct GListSel2: View {
@Bindable var patient: Patient
var body: some View {
HStack {
TextField("Gender", text: $patient.gender)
}
}
}
Hello!
Is there any way to detect when the animation appearing in iOS 18 on switching tab items completes? This applies to TabView in SwiftUI.
在webview全屏打开Video视频前后获取设备的宽高结果不同 [UIScreen mainScreen].bounds对应的设备逻辑分辨率发生变化,导致根据分辨率显示的页面显示错误
I'm currently migrating a midsize (20k LOC) project to Swift structured concurrency. With complete checking turned on, it currently builds with only two warnings, both of which are related to the QLPreviewControllerDelegate protocol:
"Main actor-isolated instance method 'previewControllerDidDismiss' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode" as well as the same warning but substituting 'previewController(_:transitionViewFor:)' for the method name.
I'm confused as to how to make these nonisolated, as they use UIKit classes/subclasses as arguments and/or return types.
I've got a List containing Colour objects. Each colour may have an associated Project Colour object.
What I'm trying to do is set it up so that you can tap a cell and it will add/remove a project colour.
The adding/removing is working, but each time I do so, it appears the whole view is reloaded, the scroll position is reset and any predicate is removed.
This code I have so far
List {
ForEach(colourList) { section in
let header : String = section.id
Section(header: Text(header)) {
ForEach(section) { colour in
HStack {
if checkIfProjectColour(colour: colour) {
Image(systemName: "checkmark")
}
VStack(alignment: .leading){
HStack {
if let name = colour.name {
Text(name)
}
}
}
Spacer()
}
.contentShape(Rectangle())
.onTapGesture {
if checkIfProjectColour(colour: colour) {
removeProjectColour(colour: colour)
} else {
addProjectColour(colour: colour)
}
}
}
}
}
.onAppear() {
filters = appSetting.filters
colourList.nsPredicate = getFilterPredicate()
print("predicate: on appear - \(String(describing: getFilterPredicate()))")
}
.refreshable {
viewContext.refreshAllObjects()
}
}
.searchable(text: $searchText)
.onSubmit(of: .search) {
colourList.nsPredicate = getFilterPredicate()
}
.onChange(of: searchText) {
colourList.nsPredicate = getFilterPredicate()
}
The checkIfProjectColour function
func checkIfProjectColour(colour : Colour) -> Bool {
if let proCols = project.projectColours {
for proCol in proCols {
let proCol = proCol as! ProjectColour
if let col = proCol.colour {
if col == colour {
return true
}
}
}
}
return false
}
and the add/remove functions
func addProjectColour(colour : Colour) {
let projectColour = ProjectColour(context: viewContext)
projectColour.project = project
projectColour.colour = colour
colour.addToProjectColours(projectColour)
project.addToProjectColours(projectColour)
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func removeProjectColour(colour: Colour) {
if let proCols = project.projectColours {
for proCol in proCols {
let proCol = proCol as! ProjectColour
if let col = proCol.colour {
if col == colour {
viewContext.delete(proCol)
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
}
}
PLATFORM AND VERSION
iOS
Development environment: Xcode 16, macOS 15.0.1
Run-time configuration: iOS 18.1
DESCRIPTION OF THE PROBLEM
I am experiencing inconsistent behaviour in SwiftUI when attempting to hide the status bar programmatically. Specifically, I want the status bar to be hidden only during the AreaQuizView, but the behaviour is not persistent across different views. On some views, the status bar hides correctly, while on others, it does not. I am using .statusBarHidden() to achieve this.
STEPS TO REPRODUCE
In AreasView, apply .statusBarHidden() to the outermost VStack. The status bar hides as expected.
In AreaQuizView, apply the same .statusBarHidden() to the outermost stack. However, in this view, the status bar remains visible.
In the Build Targets, if I set Status bar is initially hidden to YES in the info.plist, I lose control over the status bar entirely.
EXPECTED BEHAVIOUR
I would expect that .statusBarHidden() would behave consistently across all views, allowing me to programmatically hide the status bar only during AreaQuizView and leave it visible for other views.
ADVICE REQUESTED
Could you please advise on how to achieve the desired behaviour, where the status bar is only hidden during AreaQuizView? I would also appreciate any guidance on ensuring consistent behaviour across different views.
Please advise.
I have a Map in SwiftUI using MapKit and the map has several annotations and MapCircles added to it. I need to have the ability to center the map on a specific latitude and longitude. The issue is that the map instead is centering so that all annotations and MapCircles etc. are visible.
How can I have it disregard items added to the map and center the map at a specific latitude and longitude and ideally, control the zoom level of the map also?
Only IOS 18+ bug.
After tap share on UIPrintInteractionController - crash.
So:
#0 0x00000001bc38edf4 in _realizeSettingsExtension.cold.5 ()
#1 0x00000001bc310ed0 in _realizeSettingsExtension ()
#2 0x00000001bc33d100 in _ingestPropertiesFromSettingsSubclass ()
#3 0x00000001bc33be50 in __FBSIngestSubclassProperties_block_invoke ()
#4 0x00000001bc33bd7c in FBSIngestSubclassProperties ()
#5 0x00000001bc33d814 in FBSSettingForLegacySelector ()
#6 0x00000001bc30ecf8 in FBSSettingForSelector ()
#7 0x00000001bc350d98 in -[FBSMutableSceneSettings addPropagatedProperty:] ()
#8 0x00000001a64bae88 in __58-[_UISceneHostingController createSceneWithConfiguration:]_block_invoke_3 ()
#9 0x00000001c5bc16ec in -[FBScene _joinUpdate:block:completion:] ()
#10 0x00000001a64bab9c in -[_UISceneHostingController createSceneWithConfiguration:] ()
#11 0x00000001a64ba838 in -[_UISceneHostingController initWithAdvancedConfiguration:] ()
#12 0x00000001a64ba8cc in -[_UISceneHostingController initWithProcessIdentity:sceneSpecification:] ()
#13 0x00000001c05a8bd0 in -[SHSheetRemoteScene setupSceneHosting] ()
#14 0x00000001c05a88d0 in -[SHSheetRemoteScene activate] ()
#15 0x00000001c05f2e88 in -[SHSheetInteractor startSession] ()
#16 0x00000001c05ebc08 in -[SHSheetPresenter initWithRouter:interactor:] ()
#17 0x00000001c05de3c8 in +[SHSheetFactory createMainPresenterWithContext:] ()
#18 0x00000001c05d4dec in -[UIActivityViewController _createMainPresenterIfNeeded] ()
#19 0x00000001c05d6320 in -[UIActivityViewController _viewControllerPresentationDidInitiate] ()
#20 0x00000001a5a109c4 in -[UIViewController _presentViewController:withAnimationController:completion:] ()
#21 0x00000001a5a1311c in __63-[UIViewController _presentViewController:animated:completion:]_block_invoke ()
#22 0x00000001a5a0d248 in -[UIViewController _performCoordinatedPresentOrDismiss:animated:] ()
#23 0x00000001a5a0ceb4 in -[UIViewController _presentViewController:animated:completion:] ()
#24 0x00000001a5a0ccc0 in -[UIViewController presentViewController:animated:completion:] ()
#25 0x00000002001f3660 in -[UIPrintPanelViewController showSharePanelForPDFURL:] ()
In log throwing an error (I'm not 100% sure that is related - but last class in stack trace the same):
failure in void _realizeSettingsExtension(__unsafe_unretained Class, __unsafe_unretained Class) (FBSSceneExtension.m:502) : could not convert "1" to an integer
What I have is that big project with a lot of dependencies and etc..
Trying on clear project and it worked. (sharing simple local image with url).
Testing on my project:
With no controllers at all - check.
With different approaches (htm content; pdf data, image local url) - check.
With UIActivityViewController - check
With day of UIPrintInteractionController creation (not a thread/related issue) - check.
No other work can be done from my side (except rewrite 10years project).
Help me please to debug it from private api prospective as I have no Idea what is happening. (trying to remove all appearances and all dependency - not easy task).
Thanks
I have a Catalyst app that uses popovers frequently, and I'd love to have them stay active when the app loses focus. It appears this is controlled in a native AppKit app via NSPopover.Behavior. Is this functionality exposed somewhere in Catalyst?