Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

iOS 18 NavigationSplitView in NavigationStack not loading properly
With iOS 18.0, this snippet of code that has a NavigationSplitView inside a NavigationStack will not display the sidebar until the navigation transition is completed. NavigationStack { NavigationLink("Link") { NavigationSplitView { Text("Example") } detail: { Text("Does not appear") } } } Directly after pressing the link, a toolbar briefly appears. Once the transition is completed, the split view's sidebar appears and the toolbar disappears. The detail view does not visually appear at all. The same problem occurs when using .navigationDestination(…), which I am in our production code. I've tested this in Xcode 16.0 Previews for iOS 18.0, iPhone SE Simulator iOS 18.0, iPadOS 18.0 when horizontal size class is compact, and on my personal iPhone 13 mini iOS 18.0 I experienced this problem on our production app. Is there any workaround to not have this delay? Our app is heavily built around this nested approach, and has been working perfectly in previous iOS versions.
3
0
189
1w
Mapkit and swiftui
I have updated my map code so that now I have a region that is set as a state var in my strict. My map links to this state var. the problem is now I want to update my map based on my long and last variables that are passed to the struct is there a way to do this - going crazy trying to do this
3
0
4.3k
Jun ’20
SwiftData Multiple ModelConfigurations
A ModelContainer with two configurations for two seperate models with one set to isStoredInMemoryOnly:false and the other one isStoredInMemoryOnly:true crashes after insertion. Anyone git this to work? import SwiftData @main struct RecipeBookApp: App { var container: ModelContainer init() { do { let config1 = ModelConfiguration(for: Recipe.self) let config2 = ModelConfiguration(for: Comment.self, isStoredInMemoryOnly: true) container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2) } catch { fatalError("Failed to configure SwiftData container.") } } var body: some Scene { WindowGroup { ContentView() .modelContainer(container) } } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var recipes: [Recipe] @Query private var comments: [Comment] var body: some View { VStack { Button("Insert") { context.insert(Recipe(name:"Test")) context.insert(Comment(name:"Test")) } List(recipes){ recipe in Text(recipe.name) } List(comments){ comment in Text(comment.name) } } .padding() .onAppear(){ context.insert(Recipe(name:"Test")) context.insert(Comment(name:"Test")) } } } @Model class Recipe { internal init(name:String ) { self.name = name } var id: UUID = UUID() var name: String = "" } @Model class Comment { internal init(name:String ) { self.name = name } var id: UUID = UUID() var name: String = "" }
2
0
276
2w
Is there a way to know what size of icons is enabled in the home page?
Hey, i have an app that uses some calculations to replicate a transparent background in widgets, however given that in ios 18 we can now change the icons size to large, I wonder if there is a way to know what the user has currently selected and react to it? The workaround I have is that user needs to select a new config to switch the widget to large so re-calculations are done, but it would be nice if we there was a way for us to catch the new size.
0
0
113
6d
iOS18 SwiftUI Bug: Theme Change Issue
Yet another bug, I suppose, on iOS 18. This time it relates to the SwiftUI framework, and to be precise, it's about the theme change functionality. It no longer works properly on iOS 18, while it’s not an issue on iOS 17. Demo app available at: https://github.com/m4rqs/iOS18ThemeIssue Steps to reproduce: Assume the system is set to use the light theme. Go to the Settings tab. Switch the colour scheme to Dark. Switch the colour scheme to System (this no longer works). Switch the colour scheme to Light (the tab bar is not updated if the content page is long enough and go beyond current view). Switch between tabs (tab bar icons are greyed) enum Theme: Int { case system case light case dark } struct SettingsView: View { @State private var theme: Theme = .system @State private var colorScheme: ColorScheme? = nil var body: some View { Form { Section(header: Text("General")) { Picker("Colour Scheme", selection: $theme) { Text("System").tag(Theme.system) Text("Light").tag(Theme.light) Text("Dark").tag(Theme.dark) } .preferredColorScheme(colorScheme) .onChange(of: theme) { switch theme { case .light: colorScheme = .light case .dark: colorScheme = .dark default: colorScheme = nil } } } } } }
0
3
211
6d
Overzealous TextField Behavior
macOS 14.6.1, SwiftUI, Xcode 16.0 (developing for macOS) I have a TextField with a custom formatter and a custom binding (one created using Binding(get:set:). My understanding is that the TextField should only call on the formatter and update the binding when I commit the TextField by moving focus away from it, hitting return, etc. Unfortunately, that is not the case. I was able to verify that the formatter is being called (via NSLog added to the formatter code) every time I add a character to the field. Not only is this a waste of CPU resources, but in combination with the custom binding, it is causing a data entry issue for my application. I am writing a simple emulator for a computer system I concocted, and the formatter is formatting a memory location into its assembly language - the formatter's string method disassembles the instruction from the underlying memory value and the getObjectValue method assembles an input string back into the memory location. One example of an instruction would be the "set" instruction. All of these are valid forms for input to the assembler: set set 0 set x The "set" by itself is equivalent to "set 0", so what is happening is that I type "set" and the TextField immediately gets a valid response back from the formatter and updates the binding with the value of the "set 0" instruction. The custom binding updates the value in memory, which triggers the "get" method of the binding and updates the TextField with the disassembled value which helpfully adds the "0" to the field, setting it to "set 0" before I have a chance to type the "x". I need to manually delete the "0" from the line which I never typed there in the first place in order to finish typing the line of input. I either need a way to cause the TextField to behave the way it is supposed to and only update the binding when the value is committed, or a way to prevent the binding's get method from being retriggered by its own set method. Any ideas how to go about fixing this? Note that I set up a temporary TextField which was bound using a simple $binding to a state variable, and while the variable is updated whenever valid input is presented, it does not trigger the TextField to reread and thus I do not have the same input issue with that TextField. There is a reason why I need to use the custom get/set in context, however, so this is still an issue for me.
1
0
88
1w
Registering variable fonts programatically
Is there an API to register .ttf files that have variables fonts (ie one or more axes specified). CTFontManagerRegisterGraphicsFont() makes only the default variation available. The same file when specified in UIAppFonts of Info.plist makes all the variants available (confirmed by querying UIFont.fontName(forFamilyName:)) This is mostly required for registering fonts that are bundled as part of a Swift package.
0
0
191
1w
Hiding Home Bar / Swipe up bar -- how to?
I'm working on an app that will be used in laboratory conditions. The application must be as dim as possible. For all the text and buttons, I'm thus using Color(red: 0.1, green: 0.0, blue: 0.0). However, a bright Home Bar / Swipe up bar emerges whenever the user interacts with the screen. This characteristic renders the iPhone useless in those conditions. In the Android version, such problems do not exist. And, I have yet to find a solution here in this forum or elsewhere. I must force the Home Bar to be invisible or Color(red: 0.1, green: 0.0, blue: 0.0). How to do that? Can anybody help?
0
0
108
1w
NavigationSplitView(sidebar:content:detail:) does not show View in content closure
View using NavigationSplitView(sidebar:content:detail:) in SwiftUI on tvOS does not show the View in the content closure and does not allow proper navigation. This occurs when NavigationSplitViewStyle is .automatic or .prominentDetail. It also occurs when not specified. You can avoid using this sidebar style by adding .navigationSplitViewStyle(.balanced). However, I would like to build an app employing this View. I would be glad to know what you have noticed and if you have any advice. Code Here is the code to reproduce it Just replace it with this and somehow the phenomenon occurs. import SwiftUI struct ContentView: View { @State var selected:Int? @State var selected2:Int? var body: some View { NavigationSplitView { List(selection: $selected){ NavigationLink(value: 1){ Label("1", systemImage: "1.circle") } NavigationLink(value: 2){ Label("2", systemImage: "2.circle") } NavigationLink(value: 3){ Label("3", systemImage: "3.circle") } } .navigationTitle("Sidebar") } content: { if let selected = selected { List(selection: $selected2){ NavigationLink(value: 1){ Label("1", systemImage: "1.square") } NavigationLink(value: 2){ Label("2", systemImage: "2.square") } NavigationLink(value: 3){ Label("3", systemImage: "3.square") } } .navigationTitle("Content \(selected)") } else { Text("No Selected") } } detail: { Group { if let selected2 = selected2 { Text(String(selected2)) }else{ Text("No Selected") } } .navigationTitle("Detail") .frame(maxWidth: .infinity, maxHeight: .infinity) } .navigationSplitViewStyle(.prominentDetail) } } Environment tvOS 18 Simulator (22J356) macOS 15.1 beta (24B5055e) Xcode 16.0 (16A242d) How to Reproduce Open the attached project with Xcode. Build the project on Apple TV with Xcode. press any button on the sidebar Confirm that the View in the content closure is not displayed. Actual Behavior The View in the content closure is not displayed, and the View in the detail closure is displayed. (4/4) Correct Behavior The View in the content closure is displayed, and when the button of the View is pressed, the View in the detail closure is displayed.
0
0
106
1w
10162: The SwiftUI cookbook for focus - does not work as expected with iOS 18
I try to create a sheet that shows a textfield and the textfield should gain the focus immediately after the sheet is presented. This use case is explained in Session 10162 at 11:21 and at 13:31 my desired behavior is shown. I could not get this to work in my own code and downloaded the sample code from here: https://developer.apple.com/documentation/swiftui/focus-cookbook-sample Then I opened the sample code and run it in the simulator. It does not focus when the sheet appears in a iOS 18 simulator using Xcode 16 installed via the AppStore. It does gain focus if I use the "add" Button. No changes made on the sample code. Just adjusted the Team setting to get a clean build. The behavior I get locally under iOS 18 is not what is shown in the session and I can't understand why. I tried the following Simulators (and platforms) iPhone 16, iPad Pro (M4, 11inch) and my Mac. On none of those the last item got focus just by presenting the sheet. Is it not possible to test this in a simulator? Could I have a configuration error? Given all the information I found yet, this seems like a Bug. It would be very helpful if someone could replicate my problem. Thank you for your help. Programm Versions: Xcode: Version 16.0 (16A242d) MacOS: 15.0 (24A335)
0
0
97
1w
Show main window of SwiftUI app on macOS Sequoia after auto start
It seems like it is no longer possible to open the main window of an app after the app has been launched by the system if the "Auto Start" functionality has been enabled. I am using SMAppService.mainApp to enable to auto start of my app. It is shown in the macOS system settings and the app is automatically started - but the main window is not visible. How can I change this behaviour so the main window of the app is always visible when started automatically? I have not noticed this behaviour before the release of macOS Sequoia. My app is using Swift 6 and the latest version of macOS and Xcode. Regards
0
0
94
1w
New `.animation(_:body:)` overload confusion
Hi folks, I’ve been trying to use the new .animation(_:body:) overload without success. I’m attempting to animate multiple properties of a view, each with different animations. This overload seems to be the perfect candidate to achieve that. Here's the code I'm using: struct ContentView: View { @State private var isAnimating = false var body: some View { Text("Hello World") .font(.largeTitle) .animation(.easeOut(duration: 1)) { $0.foregroundStyle(isAnimating ? .red : .blue) } .animation(.linear(duration: 10)) { $0.offset(x: isAnimating ? -100 : 0) } .onAppear { isAnimating = true } } } Pretty straightforward, but I don’t get any animations at all. Of course, I could wrap isAnimating = true in a withAnimation closure, but the WWDC session about those APIs mentions this is not needed. Furthermore, if I do that, the animations I provide in .animation(_:body:) are not being used. I’m really confused by this new API, and I’m starting to think it doesn’t work as advertised.
0
1
144
1w
How to close the keyboard using SwiftUI
I've been having trouble with finding a good way to allow the user to close the keyboard. Naturally, I'd like to use the keyboard toolbar but it's so inconsistent, it's impossible. Sometimes it shows up, other times it doesn't. At the moment, it's not appearing at all no matter where I put it. On the NavigationStack, on the List inside of it, on the TextField. It just doesn't appear. I added a TapGesture to my view to set my FocusState that I'm using for the fields back to nil, however, this stops the Picker I have from working. I tried using SimultaneousGesture with TapGesture, and that didn't work. For example: .simultaneousGesture( TapGesture() .onEnded() { if field != nil { field = nil } } ) With the current setup, each TextField switches to the next TextField in the onSubmit. The last one doesn't, which will close the keyboard, but I want to give people the option to close the keyboard before that. Does anyone have a good way to close the keyboard?
0
0
122
1w
Widgets not displaying data when running on iOS 18
When I build my app on Xcode 16 and run it in an iOS 18 simulator The data downloaded in the app will not get to the widget. Same behaviour happens when running on a physical device. If I run the app in a iOS 17.5 simulator the widget gets and displays the data correctly. is there a setting that I need to change that I’ve missed? The app works perfectly on iOS 18 with a build built in Xcode 15.4
4
0
241
1w
SwiftUI: listSectionSeparator not working on macOS
Hi, When I use 'listSectionSeparator' on hide the section separator on a List 'section', it works as expected on iOS, but doesn't have any effect on macOS. Is that a known issue? Are there any workarounds for this? Here's a basic reproducible example: import SwiftUI struct TestItem: Identifiable, Hashable { let id = UUID() let itemValue: Int var itemString: String { get { return "test \(itemValue)" } } } struct TestListSelection: View { let testArray = [TestItem(itemValue: 1), TestItem(itemValue: 2), TestItem(itemValue: 3), TestItem(itemValue: 4)] @State private var selectedItem: TestItem? = nil var body: some View { List (selection: $selectedItem) { Section("Header") { ForEach (testArray, id: \.self) { item in Button { print("main row tapped for \(item.itemValue)") } label: { HStack { Text(item.itemString) Spacer() Button("Tap me") { print("button tapped") } .buttonStyle(.borderless) } } .buttonStyle(.plain) } } .listSectionSeparator(.hidden) // has no effect on macOS Section("2nd Header") { ForEach (testArray, id: \.self) { item in Text(item.itemString) } } .listSectionSeparator(.hidden) // has no effect on macOS } .listStyle(.plain) } } #Preview { TestListSelection() }
1
1
264
Jun ’24
dismissWindow alternative for macOS 13?
Currently for my SwiftUI application i'm using dismissWindow() to close my windows. However, I want to make my app compatible on macOS 13 to enable a wider audience. My current usage of this function is as follows: func reloadContentViewAfterDelete() { @Environment(\.openWindow) var openWindow @Environment(\.dismissWindow) var dismissWindow dismissWindow(id: "content") openWindow(id: "content") }
1
0
124
1w
users Widgets disappear!!! Xcode 16
Some users have reported that the app's widgets have disappeared after we updated to the latest Xcode for iOS 18 development. They are unable to find our app in the widget search, which prevents them from re-adding the widget. We were unable to reproduce this issue on our own devices during testing. Could this be a system bug? Have others encountered a similar issue?
7
5
304
2w
SwiftUI toolbar in MacOS 15 bug ?
struct ContentView: View { var body: some View { NavigationSplitView { List { Text("row 1") Text("row 2") Text("row 3") } .toolbar(content: { ToolbarItem { Button("aa", action: onToolbar) } }) } detail: { HSplitView { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .toolbar(id: "toolbar", content: { ToolbarItem(id: "toolbar-1") { Button("bb", action: onToolbar) } }) .padding() Text("right") } }.navigationTitle("") } func onToolbar() {} } Run & Crash NSToolbar 0x6000005665b0 already contains an item with the identifier com.apple.SwiftUI.splitViewSeparator-0. Duplicate items of this type are not allowed.
8
0
301
2w
iOS 18 Control Widget Button won't open app
XCode Version 16.0 (16A242d) iPhone 12 - iOS 18 (22A3354) Macbook Air M1 - Sonoma 14.6.1 I am currently working on building Control Buttons for our app and I have consistently run into the same issue: Unknown NSError The operation couldn’t be completed. (LNActionExecutorErrorDomain error 2018.) This error can be found in the following posts: Apple Developer Forums - Post 1 Apple Developer Forums - Post 2 Apple Developer Forums - Post 3 StackOverflow - Post 4 Github - Post 5 I've tried every single solution recommended within these posts, however nothing has worked successfully so far. Additionally, I've tried the using .widgetUrl() on the Label() within the ControlWidgetButton like so: ControlWidgetButton(action: JournalControlIntent()) { Label("Open App", systemImage: "pencil.line") .widgetURL(URL(string: "app://control/page")) } But this did not work either. Using the recommended approach to open the app as seen here: https://developer.apple.com/documentation/widgetkit/creating-controls-to-perform-actions-across-the-system#Open-your-app-with-a-control simply won't work since we have a Flutter app with deep linking setup. Meaning the only option is launching either a deep link or universal link. Our URL scheme is setup correctly since it's currently working for our iOS Widgets & Shortcuts(which use widgetURL & openURL). In Post 3, the accepted answer mentions that the control file must have the Target Membership with the App and Widget Targets to work. When I try using this solution the build fails without any errors(until you run it in VSCode where there are many errors about Derived Data - Deleting the derived data doesn't fix this error) I'm wondering if I have added the Control Widget to the incorrect folder within my XCode project? Since if you use the approach of creating a Control through XCode(File > New > Target > Widget Extension > "Include Control" > Next) it creates a top level directory in the project similar to a Stickers or Watch extension. My Control Widgets currently reside in the [App] Widgets > Control Buttons > Control Button.swift. It's then added to my main widget definition(App Widget > App_Widget.swift): @main struct App_Widget: WidgetBundle { var body: some Widget { App_Widget() // works App_Widget_One() // works if #available(iOSApplicationExtension 18.0, *) { ControlButtonOne() // does not open app ControlButtonTwo() // does not open app } } } Thank you for your help and time!
1
0
231
1w
SwiftUI Charts not working in Xcode 16 Beta 2
Is there a way to workaround this issue? Can I revert back to Beta 1? Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK.
1
1
193
1w