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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Integrate with the system provided Workout Live Activity in the Apple Watch Smart Stack
When I start a workout in my app, the system shows a Live Activity in the Smart Stack like in the picture. My app opens if I tap on it, but the pause and resume buttons doesn't do anything. I have implemented the PauseWorkoutIntent and ResumeWorkoutIntent which works with the Action Button. I guessed that these would be used from this Live Activity as well, but it seems like not. Has anyone successfully integrated with this? I haven't seen it documented anywhere, although I think it was already included in watchOS 10. This is also shown when using the built in workout app and for that the buttons work as expected.
0
0
14
1h
onDisappear (or similar) for macOS Settings/Preferences screen
Hi All, this question has been asked before by others, without any success so far. I'm using the following (standard) method to open the system provided settings screen for my macOS (only) app in SwiftUI. var body: some Scene { Settings { PreferencesView() } if #available(macOS 13, *) { // MenuBarExtra requires macOS 13, but SettingsLink used in here requires macOS 14 MenuBarExtra("...", image: "...") { ... // this one requires macOS 14 if #available(macOS 14, *) { SettingsLink() { Text("Settings...") } } else { Button { NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) } label: { Image(systemName: "gear") } } } } } I want to know when the settings window closes. onDisappear does not work as the settings window is not really closed, but hidden. So the view stays active. All other hacks I have found neither work. Does anyone have any idea?
0
0
37
10h
SwiftUI Previews broken on local Swift Package with dependencies
I have a project with two local packages One client package with an interface and some models with dynamic type in the Package.Swift One feature package with the UI and a dependency to the client package When I try to preview a view that is not using any models or code from the client package, it loads just fine e.g. a view that is just a container to display things like a card But when I tried to preview any other view that actually uses models from the client package, it just fails the first few lines of the preview error display LinkDylibError: Failed to build <filename>.swift Linking failed: linker command failed with exit code 1 (use -v to see invocation) ld: warning: search path '/Applications/Xcode-15.4.0.app/Contents/SharedFrameworks-iphonesimulator' not found Undefined symbols for architecture arm64: Also, I'm using Xcode 15.4 and iOS 17 as the min version
0
0
39
17h
UI not dynamically updating from push notifications fetchdata function
Hi All, I really need your help, I have been racking my brain to work out why, after a push notification triggers a fetchdata function from the server, my new bookings dont dynamically update the counter against the booking types. print("Received remote notification: \(userInfo)") if let dataInfo = userInfo["data"] as? [String: Any], let jsonData = try? JSONSerialization.data(withJSONObject: dataInfo) { print("Processing data from notification...") DispatchQueue.main.async { self.eventsViewModel.updateFromPushNotification(data: jsonData) { result in completionHandler(result) } } } else { print("Failed to parse notification data") completionHandler(.noData) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register for remote notifications: \(error)") } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("Will present notification: \(notification.request.content.userInfo)") DispatchQueue.main.async { self.eventsViewModel.fetchData() } completionHandler([.banner, .badge, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Did receive notification response: \(response.notification.request.content.userInfo)") let userInfo = response.notification.request.content.userInfo if let fetchNeeded = userInfo["fetchNeeded"] as? Bool, fetchNeeded { print("Initiating data fetch due to user interaction...") DispatchQueue.main.async { self.eventsViewModel.fetchData() } } completionHandler() } @Published var bookings: [AnyBooking] = [] @Published var newBookings: [AnyBooking] = [] @Published var calendarBookings: [String: [AnyBooking]] = [:] @Published var selectedBooking: AnyBooking? private var cancellables = Set<AnyCancellable>() private let calendarManager = CalendarManager.shared // Add calendarManager func fetchData() { guard let url = URL(string: "https://allsound.wisewms.uk/webhook_get") else { print("Invalid URL for webhook request") return } var request = URLRequest(url: url) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in guard let self = self else { return } if let error = error { print("Error fetching data: \(error.localizedDescription)") return } if let data = data, !data.isEmpty { if let newBookings = self.processBookings(data: data) { DispatchQueue.main.async { self.bookings = newBookings self.separateAndOrganizeBookings(bookings: newBookings) } } else { print("Failed to process bookings.") } } else { print("No data received from server.") } } task.resume() } @main struct AllSoundApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @StateObject var eventsViewModel = EventsViewModel() @Environment(\.scenePhase) var scenePhase @AppStorage("selectedTheme") private var selectedTheme: Theme = .system var body: some Scene { WindowGroup { ContentView() .environmentObject(eventsViewModel) .environmentObject(appDelegate.navigationCoordinator) .preferredColorScheme(selectedTheme.colorScheme) .onChange(of: scenePhase) { oldPhase, newPhase in if newPhase == .active { eventsViewModel.fetchData() } } } } }
2
0
46
17h
Interactive Live Activity in watchOS 11 - not getting AppIntent buttons to work
I have started to work on adding Live Activities to my app in watchOS 11. The app already has interactive Live Activities on the phone that works as expected. I have added a view for the activityFamily: small and it shows up as expected. My problem is that buttons doesn't work. I use the Intent based button, and on the iPhone Lock Screen they work. On the watch, nothing happens. Has anyone got this working? Not sure if I'm missing something or if it's a bug.
1
0
49
21h
AttributeGraph: cycle detected Warning with WatchOS app
I've been seeing warning like the following with my Apple Watch app: === AttributeGraph: cycle detected through attribute 140952 === === AttributeGraph: cycle detected through attribute 131640 === === AttributeGraph: cycle detected through attribute 131640 === === AttributeGraph: cycle detected through attribute 131640 === === AttributeGraph: cycle detected through attribute 131640 === === AttributeGraph: cycle detected through attribute 131640 === === AttributeGraph: cycle detected through attribute 131640 === I've done some debugging with Instruments and Xcode, I've determined that its caused by adding a .toolbar { ToolbarItemGroup(placement: .topBarTrailing) { Label("Stop", systemImage: "xmark") } } to an item within my NavigationSplitView List Destination view. To aid reproduction of this issue even more, I've verified the same warning occurs with the Apple sample code from the WWDC23 Backyard Birds app. https://developer.apple.com/documentation/swiftui/backyard-birds-sample?changes=_9 If you take the Apple sample code, open it in Xcode 15.4 and run it in the Apple Watch WatchOS 10.5 simulator, then select the Bird Springs item, all is well. If you then add the above toolbar code to the BackyardSummaryTab file at the bottom of the VStack, you'll see the same AttributeGraph issues I'm seeing in my app. Is this a bug? I can't understand why adding a static ToolBarItem in WatchOS is causing this. I've seen this issue in the simulator and also on device.
1
0
70
1d
TipKit vs. Swift 6 + Concurrency
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1. The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit): struct ParameterRuleTip: Tip { // Define the app state you want to track. @Parameter static var isLoggedIn: Bool = false Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state. Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this. The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
2
1
100
1d
TextField("x", value: $y, format: .currency(code: "USD")) Behaves oddly
Hello, If we have the following code: import SwiftUI struct ContentView: View { @State private var usdAmount = 0.0 var body: some View { VStack { Text("Currency Form") Form { TextField("Dollar Amount", value: $usdAmount, format: .currency(code: "USD")) // 1 // TextField("Dollar Amount", value: $usdAmount, format: .number) // 2 .keyboardType(.numberPad) } Text("usdAmount = \(usdAmount)") } .padding() } } When the line marked // 1 is left uncommented (the TF has a .currency() formatter applied) the behaviour of the TF is rather odd. Upon display it shows US$0.00 Upon editing the value the US$ part remains. So if the user enters US$123 the value is not stored into the usdAmount property. The User must delete all the existing text and enter e.g. 456.78 and then the value is stored to the usdAmount property. When Line //1 is commented-out and line //2 is uncommented then the TF behaves correctly because the TF value is just 0 on first display. Should we not use the .currency() format? Or am I using it wrong? Thanks.
2
0
73
2d
.searchble Keyboard Incorrectly Showing After Presenting Popup
I have a list view that is accessed by pressing a button from a pervious view, all are which are in a NavigationView from the Main view. For this list view I have applied the .searchable tag to allow users to search through the list. When a user taps on an item in the list a .sheet will present to present a more detailed overview. The issue happens that if a user searches for an item in the list, and taps on the item to present the sheet the keyboard will disappear while the sheet presents but then pop back up despite still editing the search bar on the list view. Currently, my view is roughly set up like this. var body: some View { ThemesListView } .sheet(item: $presentedSheetTheme, onDismiss: { fetchedThemes.nsSortDescriptors = themeListSort.nsSortDescriptorObject }) {themeToPassOn in EditThemeView(themeToEdit: themeToPassOn) } var ThemesListView: some View { List { Button(action: { presentedSheetTheme = theme } } .searchable(text: query, placement: .navigationBarDrawer(displayMode: .always)) } I have tried many things to fix this, even finding this thread (https://forums.developer.apple.com/forums/thread/746826) however none of the solutions were any help. Here is a link (https://imgur.com/a/KKJ27iY) to a video of the issue. This issue seems to be fixed in some iOS versions such as 17.0 and 18.0 Beta 1 however many other versions such as 17.4 or 17.5 still experience this issue meaning I still need to fix it for these versions. Any help would be greatly appreciated, thanks!
0
0
60
2d
NavigationBar Back Button Color
I am trying to change the colour of the "Back" from blue to white but having difficulty do so, if anyone can suggest me a better way to do it would be grateful. "import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = UIColor(red: 0.216, green: 0.776, blue: 0.349, alpha: 1) appearance.titleTextAttributes = [.foregroundColor: UIColor.white] appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance UINavigationBar.appearance().tintColor = .white return true } }"
1
0
107
2d
No containerBackground content on Widget in iOS 18 tinted home screen style
The widget I have create for iOS 17 uses the containerBackground to display an image in the background. This works fine. But when I set the home screen to the iOS 18 tinted option the background disappears. I want the background to stay because it contains an image of that is meaningful to the user. I use the following code: @ViewBuilder var body: some View { if let memory = entry.memory, let uiImage = memory.image { Group { if entry.showCaption { memoryBody(with: memory) } else { Color.white.opacity(0.0000000001) } } .foregroundStyle(.white) .widgetBackground( Image(uiImage: uiImage) .resizable() .scaledToFill() ) } else if let memory = entry.memory { memoryBody(with: memory) .widgetBackground(Color.gray) } else { noMemoryBody() } } extension View { func widgetBackground(_ backgroundView: some View) -> some View { if #available(iOSApplicationExtension 17.0, *) { return containerBackground(for: .widget) { backgroundView } } else { return background(backgroundView) } } }
3
1
95
2d
selection multiple buttons
struct Question { var title: String var options : [String] } struct SimpleQuestions: View { @State var selectedOption = "" @State var question = Question(title: "question title", options: \["one", "two", "three"\]) var body: some View { VStack { Text(question.title) ForEach(question.options, id: \.self) { option in HStack { Button { selectedOption = option } label: { Circle() .foregroundStyle(selectedOption == option ? .blue : .gray.opacity(0.5)) .frame(width: 23, height: 23) }}}}}
2
0
66
2d
CommandGroup, Xcode 16b1, and Swift 6
I suspect this will be a "wait for the next beta" item, but thought I'd throw it out here in case anyone knows of a workaround. Mac app compiling under Xcode 16 beta 1. Trying to get rid of all warning that would stop the adoption of Swift 6 -- Strict Concurrency Checking is set to Complete. I'm down to one warning before I can enable swift 6. SwiftUI.Commands Main actor-isolated static method '_makeCommands(content:inputs:)' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode That's because I've added menu commands to the app. It's very easy to reproduce. import SwiftUI @main struct CommandApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { HelpCommand() } } } struct HelpCommand: Commands { var body: some Commands { CommandGroup(replacing: .help) { Button("Help me") { // } } } } The suggested fix is telling me what change I should make ot _makeCommands. At least that is how I'm reading it.
0
0
94
3d