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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Complication Widget using AccessoryWidgetGroup
I want to get which button in AccessoryWidgetGroup was pressed in the Watch App, but I can't. When I use Button(_:intent:), it works in Smart Stack, but it doesn't work in Complication Widget. Using widgetURL(_:) always gets the URL of the first button. Below is a snippet of the code I tried. All codes can be found here. struct MyWatchWidgetEntryView : View { var entry: Provider.Entry var body: some View { AccessoryWidgetGroup("Widget Group") { MyWatchWidgetEntryButton(intent: .init(id: "001", imageName: "star.fill")) MyWatchWidgetEntryButton(intent: .init(id: "002", imageName: "heart.fill")) MyWatchWidgetEntryButton(intent: .init(id: "003", imageName: "leaf.fill")) } } } //Button View private struct MyWatchWidgetEntryButton: View { @Environment(\.showsWidgetContainerBackground) var showsWidgetContainerBackground let intent: MyAppIntent var body: some View { Button(intent: intent) { ZStack { if showsWidgetContainerBackground { Color.black } else { AccessoryWidgetBackground() } VStack { Image(systemName: intent.imageName) .font(.headline) Text(intent.id) .font(.system(size: 10, weight: .bold)) } } } .buttonStyle(.plain) .widgetURL(URL(string: "widget://" + intent.id)) } } Does anyone know how to do this? Thank you.
3
0
114
2d
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
99
3d
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
2
161
3d
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
78
3d
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
174
4d
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
98
4d
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
95
4d
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
84
4d
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
79
4d
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
126
4d
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
111
5d
Tinted widgets have an inset background in the widget gallery only
When the home screen is in tinted mode in iOS 18, the widget gallery seems to display widgets with the background inset from the edge of the widget (i.e. negative padding). You can see this behavior in the Apple News widget too, where the full-bleed content outside of the inset is very light. This only happens in the sample gallery, not when the widgets are placed on the home screen. For my widgets, this outer edge contains important content and the clipping behavior makes the widgets look poorly designed when viewed in the gallery. Is there any way to turn this behavior off and just show the widget normally in the gallery with no weird inset — the way it will actually display when added to the home screen? If it matters, my widgets are currently configured with: .contentMarginsDisabled() .containerBackground(for: .widget) { // ... (background color) */ }
1
0
100
5d
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
0
145
5d
#Preview a Widget placeholder?
While I am able to use #Preview to preview a Widget, it seems to be not possible to easily preview a Widget placeholder. With a "classic" preview I can use .redacted(reason: .placeholder), but this has limitation e.g. it will ignore .contentMarginsDisabled() struct MyWidget_Previews: PreviewProvider { static var previews: some View { Group { MyWidgetView(entry: SimpleEntry(date: .now, emoji: "😀")) MyWidgetView(entry: SimpleEntry(date: .now, emoji: "😀")) .redacted(reason: .placeholder) } .previewContext(WidgetPreviewContext(family: .systemMedium)) .containerBackground(.white, for: .widget) } } If I use #Preview, the .redacted modifier won't work, and I seem to have to put it in the MyWidget implementation. #Preview(as: .systemMedium) { MyWidget() } timeline: { SimpleEntry(date: .now, emoji: "😀") SimpleEntry(date: .now, emoji: "🤩") } Am I missing something?
1
0
121
5d
NavigationSplitView's toolbar item disappears on resize
When a NavigationSplitView's sidebar has a default selected value, the detail's toolbar item disappears when resizing the view from compact to regular size. @State private var selectedId: String? = "anything" NavigationSplitView { List(selection: $selectedId) { Text("Sidebar") } } detail: { Text("Detail") .toolbar { Button("Button") {} } } There is no way to get the toolbar item back, other than reloading the view. I have no idea why this happens. In my example I have a dummy Text("Sidebar") without a value, but the problem occurs regardless of its content. Tested on Simulator iPadOS 18.0, and I've seen this happen in our production app.
3
0
111
5d
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
150
6d