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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

WeatherKit Historical Data Request Limited to 10 Days
Until recently, I was unable to use WeatherKit to obtain historical Daily data. Now, it appears that I can retrieve Daily and Hourly historical data, but the returned data is limited to a ten day period. No matter what start and end dates are included, I get data from start date to 10 days later (assuming the end date was more than 10 days after the start). Is this a permanent restriction? Example: let historicalData = try await weatherService.weather(for: location, including: .daily(startDate: startDate, endDate: endDate))
2
1
1.4k
Nov ’23
Having Trouble passing a ButtonStyle as a parameter to a func
I have a SwiftUI View where the body looks like this              VStack {                   VStack(spacing: 4) {                     Text("Outline")                     Button("Tap Me") {                       print("tapped")                     }                     .buttonStyle(.outline)                   }                   VStack(spacing: 4) {                     Text("Simple")                     Button("Tap Me") {                       print("tapped")                     }                     .buttonStyle(.simple)                   }                 } So to remove the duplication, I want to do something like this:      func textButton(title: String, buttonStyle: ButtonStyle) -> some View {       VStack {         Text(title)         Button("hello") {           print("tapped")         }           .buttonStyle(buttonStyle)       }     } The compiler asks me to add 'any' before ButtonStyle. When I do that I get the following: "Type 'any View' cannot conform to 'View'" It works fine if I don't pass in the ButtonStyle. Any suggestions on how to pass a ButtonStyle into a func? thanks, in advance!
2
1
1.6k
Jan ’24
iOS: List selection is reset to nil when app is sent to background
For some reason, a List will reset its selection to nil when the app is in the background. Steps to reproduce the issue: Run attached sample project Once the app has launched, select a name in the sidebar Move the app to the background Wait a few seconds Bring back the app to the foreground Expected result: The list selection should still be valid Actual result: The list selection is set to nil Notes: I’m using a StateObject, which should be the way to ensure that data isn’t regenerated when views are rendered. Is this a bug or something else needs to be taken care of? class AppModel: ObservableObject {     @Published var selectedPerson: Person? } @main struct NilListSelectionApp: App {     @StateObject var appModel = AppModel()     var body: some Scene {         WindowGroup {             ContentView()                 .environmentObject(appModel)         }     } } struct Person: Identifiable, Hashable {     let id: UUID     let firstname: String     init(firstname: String) {         id = UUID()         self.firstname = firstname     } } struct ContentView: View {     @EnvironmentObject private var appModel: AppModel     var body: some View {         NavigationSplitView {             SidebarView()         } detail: {             PersonView(person: appModel.selectedPerson)         }     } } struct SidebarView: View {     @EnvironmentObject private var appModel: AppModel     private let persons = [Person(firstname: "Joe"), Person(firstname: "Jane")]     var body: some View {         List(persons, id:\.self, selection: $appModel.selectedPerson) { person in             Text(person.firstname).tag(person)         }         .listStyle(.sidebar)     } } struct PersonView: View {     let person: Person?     var body: some View {         if let person {             Text(person.firstname)         }         else {             Text("No Selection")         }     } }
10
2
2.1k
Jul ’23
iOS 16.2 breaks ProgressView(timerInterval:countsDown:) on Dynamic Island or on Always-On Lock Screen
I used ProgressView to display a countdown progress bar in a Live Activity. However, I found that since iOS 16.2, ProgressView(timerInterval:countsDown:) does not update properly in the following situations. on Dynamic Island (either Expanded or CompactLeading/Trailing) on the Locked Screen, after the display is turned off (isLuminanceReduced == true) In these situations, the ProgressView for the countdown is always displayed at 100% and does not automatically update with the time. The problem only occurs in iOS 16.2. And it's confusing for users. Will it be fixed please?
1
2
1.6k
Aug ’23
.keyboardShortcut on Button in Swift doesn't properly rerender unless button.label changes
here is minimal reproducible example: import SwiftUI struct ContentView: View {   @State var options = ["1","2","3","4"]   @State var option = "1"   var body: some View {     ForEach(options, id: \.self) { item in       Button(item, action: {         self.option = item       })     }     ChildView(model: .init(option: option))   } } class ChildViewModel: ObservableObject {   @Published var option: String   init(option: String) {     self.option = option   } } struct ChildView: View {   @ObservedObject var model: ChildViewModel   var body: some View {     Text(model.option)     Button("Tab", action: {       print("Option: \(model.option)")     })     .keyboardShortcut("f")   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } Here is steps to reproduce: click "2" item click "Tab" Button, which will prints "Option: 2" press Cmd+F, which will prints "Option: 1" step(3) is unexpected behavior, since it has to print "Option: 2" If you change Button("Tab") into Button("Tab (model.option)"), step 3 will produce proper result of printing "Option: 2" So i assume this is issue of keyboardShortcut not properly referencing "latest" action - unless "label" of button changes, keyboardShortcut does not use latest "action" that is given. but as you can see from example, clicking button will result calling latest action
4
2
614
Jul ’23
View like the camera app
Hello all, I would like to understand how to create a SwiftUI View like the official camera app. When the device orientation changes, the view is not animating, and the buttons just rotate (4:3, 1x...). The camera app view is compose by flash and live buttons, camera preview, config buttons, and big button to shot the photo. In portrait, it is from top to bottom, in landscape, from left to right. Also, when the last pictures view is shown, it is adapted to the current orientation, like if the camera preview view was rendered in the same device orientation. Ideas? Thanks!
2
0
2.1k
Oct ’23
Navigation bar title jumping between large and inline
I've noticed some issues with changing the navigation bar title display to inline and it is different on devices in the simulator. For iPhone 14, when navigating back from a view that set the display to inline, the navigation title "Menu" stays in inline mode for a short (500ms) delay and then jumps (no animation) back to large. On an iPhone 8, when navigating back, the title stays in inline mode instead of transitioning back to large. Even setting the display mode to large on the first item in the nav stack doesn't have any effect on correcting the behavoir. Additionally, using a Picker with inline style works just fine. It seems to be isolated to NavigationLink with the view setting inline for the title bar display mode.
7
5
2.0k
Oct ’23
SwiftUI Preview Won't Load
Hi, I am starting a new project in SwiftUI and created a new project but the preview won't load. I have not touched the code, it is as the project was created by Xcode. I am on the latest (non-beta) version of both Xcode and Mac OS. There are not any errors and the project runs successfully on physical devices but doesn't seem to run on simulators. In the upper middle right of Xcode it says "Preparing iPhone Simulator for Previews" with a loading symbol. However it has been loading for over 12 hours at this point. I will provide a screenshot showing this and what the preview window looks like for me. I am not sure what I need to do to get the preview working. Thank you in advanced for any help and let me know if you need more information.
1
0
512
Oct ’23
Swift UI Table - Problems removing selection from row
Hi,i have been trying out SwiftUI Table and wanted to present a details view when click on Table Row occurs, but I couldn't figure out how to "deselect" row once its been selected, while it may not be what Table was intended for, but I still think this code should be valid. (iPadOS) struct Person: Identifiable { let givenName: String let familyName: String let emailAddress: String let id = UUID() } private var people = [ Person(givenName: "Juan", familyName: "Chavez", emailAddress: "juanchavez@icloud.com"), Person(givenName: "Mei", familyName: "Chen", emailAddress: "meichen@icloud.com"), Person(givenName: "Tom", familyName: "Clark", emailAddress: "tomclark@icloud.com"), Person(givenName: "Gita", familyName: "Kumar", emailAddress: "gitakumar@icloud.com") ] @State private var selectedPeople: Person.ID? @State private var detailsViewPresented: Bool = false var body: some View {         Table(people, selection: $selectedPeople) {             TableColumn("Given Name", value: \.givenName)             TableColumn("Family Name", value: \.familyName)             TableColumn("E-Mail Address", value: \.emailAddress)         }         .onChange(of: selectedPeople) { selection in             guard selection != nil else {                 return             }             detailsViewPresented = true         }         .sheet(isPresented: $detailsViewPresented, onDismiss: {             // Trying to reset the selection             self.selectedPeople = nil         }) {             Text("Person's details")         } } Here when I press row, it gets selected and Text is presented, but row still remains selected, and yes, I could just use onTapGesture within row content if I declared TableColumn with explicit content, but it would just be added to that column and would not provide build in selection style. https://developer.apple.com/documentation/swiftui/table
1
0
1.3k
Jul ’23
Text view with .timer style expands too much in Live Activity
I'm implementing a Timer in my app and I want the countdown to show up as a Live Activity. It works, but I get a very weird expanding effect on the Text view. The screenshots below show the issue, I can't tell if it's a bug or if I'm doing something wrong. My goal is to shrink the live activity black area so that it's a smaller, more reasonable size. There's no reason for it to be as large as it is on the trailing side. The Live Activity code (very basic):   } dynamicIsland: { context in        } compactTrailing: { // Important bit is here            Text(Date(), style: .timer)        }    } Which renders like this, with a lot of space after the timer: Adding a background color shows the view is expanding: Text(Date(), style: .timer)     .background(.red) And if I replace the timer with a standard text view, then no issue: Text("Hello")        .background(.red) Getting out of live activities and showing a standard timer view, there is no expansion issue: struct TestView: View {     var body: some View {         Text(Date(), style: .timer)             .background(.red)     } } So... I'm stumped. Any advice is appreciated.
5
5
2.1k
Sep ’23
Hand tracking to fbx
i saw there is a way to track hands with vision, but is there also a way to record that movement and export it to fbx? Oh and is there a way to set only one hand to be recorded or both at the same time? Implementation will be in SwiftUI
1
0
988
Mar ’24
SwiftUI Navigation Bar appears behind Status Bar
We have a NavigationView embedded within a TabView, like this: TabView(selection: $tabSelection) { NavigationView { When a view gets pushed onto the stack in the NavigationView, the NavigationBar appears too high, almost under the StatusBar, as shown in the attached picture. If you touch the StatusBar, somehow it alerts the NavigationBar to scoot downward into its correct position. I discovered a hack where I quickly toggle the StatusBar off, then back on, which accomplishes the same thing. My question, though, is why is this necessary? Why isn't the NavigationBar in the correct place to begin with? Here's the hack that fixes it: .onAppear { withAnimation(.linear(duration: 0.3)) { appViewModel.hideStatusBar.toggle() } DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { withAnimation(.easeInOut(duration: 0.3)) { appViewModel.hideStatusBar.toggle() } } }
2
0
756
Dec ’23
Menu works fine in iPad and Mac Catalyst but crashed on Apple Silicon
Hi, I have an iPad app that has menus, like:  CommandGroup(replacing: .help) {                 Button("Help") { showHelp = true }                     .keyboardShortcut("/")  } They works fine in iPad and also if compiled to Mac Catalyst, but will crash on Apple Silicon Mac when selected the menu items with errors like: [General] -[_UIEditMenuInteractionMenuController propertyList]: unrecognized selector sent to instance 0x600000190540 I did not use storyboard and only use SwiftUI. Any suggestions? Note: of course the best solution is to compile to Mac Catalyst, but the app has some other issues when run in Mac Catalyst. So I can only release it as iPad app.
5
0
1.4k
Oct ’23
Touch layout not matching UI layout on iPhone after waking device when .sheet is open
In a SwiftUI app on iPhone when the device is put to sleep by pressing the power button, while the app is presenting a .sheet, waking the device will result in the touch layout to not match the UI layout. See attached project to reproduce the issue. This happens with Xcode 14.2, targeting iOS 16.0. Steps to reproduce (assuming the app has been built an running on a real device, xcode project linked at the bottom): Tap the “Hello World” button. This opens a plain sheet with a fully green color content Push the device’s power button to put it to sleep Push the device’s power button again to wake the device Optionally unlock the device if needed Dismiss the opened green sheet (the app should still be open and displaying the sheet after waking the device) Try to tap the “Hello World” button again. Observed behavior: the area required to tap to activate the button no longer matches the UI and you have to tap below the button to activate it. Desired behavior: after waking the device and dismissing the sheet, the touch and ui layout should still be correct. Demonstration XCode project
9
3
2.7k
Sep ’23
didReceiveRemoteNotification Method in AppDelegate never called
Dear fellow developers, I have an issue where my didReceiveRemoteNotification method in the AppDelegate is never called. Here's what I did: I am developing a SwiftUI application for iOS 15 and 16 and am currently running tests in an iPhone 14 Pro Simulator. My Xcode version is 14.2 and the simulator is running iOS 16.2. I am of course talking about the AppDelegate's application:didReceiveRemoteNotification:fetchCompletionHandler: method, not the deprecated one. I embedded the AppDelegate in the following way: @main struct MyApp: App {     @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate ... } The integration of my AppDelegate does work in general, meaning the didFinishLaunchingWithOptions is called. I added the background modes capability to my app, including both "Remote notifications" and "Background processing". With this configuration, I would expect the AppDelegate's method to be called. I tried sending different push notifications with different payloads and headers while having the app both in the background and foreground but without success. Just to rule out mistakes on my side that are obvious to someone else, this is how I embedded the method into my AppDelegate: class AppDelegate: UIResponder, UIApplicationDelegate { ... func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { print("Method called!") completionHandler(.noData) } } And here are a few payloads and headers that I tested. I tried all of the following payloads with the following headers in any combination. apns-push-type=alert or apns-push-type=background apns-priority=5 or apns-priority=10 Example 1: Visible notification { "aps": { "alert": { "body": "Test" }, "badge": 1, "content-available": 1 }, "test": "data" } Example 2: Silent notification without badge update { "aps": { "content-available": 1 }, "test": "data" } Example 3: Silent notification with empty alert block and badge update, based on ideas from this thread { "aps": { "alert": {}, "badge": 0, "content-available": 1 }, "test": "data" } As I said, no matter whether my app is in the foreground or background, the method is never called. At the same time, the userNotificationCenter(_:willPresent:withCompletionHandler:) method of the UNUserNotificationCenterDelegate is called when the app is in the foreground. At this point, I am running out of ideas what I could possibly be doing wrong, so I hope someone else has an idea what else to try.
9
5
3.7k
Sep ’23
SwiftUI 5 | TabView issue
Hello, All. I am having an issue I just can seem to correct. My app is setup with a TabView. It has 5 tabs at the bottom. When I start the app fresh, the first(main) tab, 3rd tab, and last tab all work fine when selected. However, if I select the second or fourth tab, there is a 6 second delay before transitioning to that tab. In the console, after selecting either the second or fourth tab, once the view shows after the 6 second delay, it states: Gesture: System gesture gate timed out. Can anyone provide any information as to why this is happening? Thank you.
2
0
671
Sep ’23
Button Labels in MenuBarExtra not showing images/icons
As the title suggests, the icons/images in labels are not appearing in the MenuBarExtra Here is the code I'm running: import Combine import SwiftUI class TimerViewModel: ObservableObject { private var assignCancellable: AnyCancellable? = nil @Published var somelist: Array<String> = ["default"] init() { assignCancellable = Timer.publish(every: 5.0, on: .main, in: .default) .autoconnect() .map { String(describing: $0) } .assign(to: \TimerViewModel.somelist[0], on: self) } } @main struct mbe_testingApp: App { @State var clickCount = 0 @ObservedObject var timerOutput = TimerViewModel() var body: some Scene { MenuBarExtra("mbe test", systemImage: "\(clickCount).circle") { Button() { clickCount += 1 print("incremented") } label: { Label("Increment", systemImage: "plus.square.fill") } Button() { if clickCount > 0 { clickCount -= 1 } print("decremented") } label: { Label("Decrement", systemImage: "minus.square.fill") } Button() { print("clicked") } label: { Label(timerOutput.somelist[0], systemImage: "clock") } } } } which results in a menu that looks like: What am I missing to make the label images appear alongside the text on the menu buttons?
1
0
585
Sep ’23
SwiftUI app crashes while scrolling section in List via ScrollViewReader
In our SwiftUI application , we are using List in one of our screen. We have a requirement to scroll to specific section header. Below code works fine till iOS16 and from iOS16 onwards we are getting the app crash. Can anyone suggest me any probable solution to achive this ?.         ScrollViewReader { proxy in             List {                 ForEach(Array(viewModel.newSections), id: .self) { sectionName in                     Section(header: VStack { LeaguesScheduleListSectionView(text: sectionName) }) {                         ForEach(viewModel.newRowsPerSection[sectionName] ?? []) { leagueScheduleEvent in                             LeaguesScheduleListRowView(leagueSchedule: leagueScheduleEvent)                         }                     }                     .id(sectionName)                 }             }             .listStyle(.plain)             .onAppear(perform: {                  if viewModel.newSections.contains("Today/Ongoing"),                  viewModel.newRowsPerSection[("Today/Ongoing")]?.count ?? 0 > 0 {                  proxy.scrollTo("Today/Ongoing", anchor: UnitPoint.topLeading)                  }             })         }
2
0
794
Dec ’23
When SwiftUI View is Equatable - questions...
I need to optimize my SwiftUI code, and views conforming to Equatable seem to a good way forward. However, I have some questions, that could be also an interest of others. View can conform to Equatable, and NOT encapsulated in EquatableView nor .equatable() view modifier, and modern SwiftUI implementations still can use the Equatable functionality, right? When view contains @ObservedObject or @EnvironmentObject, then static func == (...) have to handle the changes of the observed objects, otherwise the view is not updated after the observed object published change. At least this is my experience. Correct? Does view, that is Equatable, need to care about equality of its subviews? I hope no. I hope that view can evaluate equality only based on properties available to it, and SwiftUI takes responsibility for its subviews. I. e.: Even when some view returns true on ==, but something changes in its subview (detail hidden to the view), SwiftUI is able to recognize the change and takes appropriate actions. Correct? When view returns true on equality check (==), but some environment value changes (not visible to the view), the view still reflects the change. Correct? When the observed object conforms to Equatable, it is being used by SwiftUI. For what purpose? In most (if not all) cases, lhs and rhs are the same instance, so == returns true.
1
0
998
Nov ’23
SwiftUI’s LongPressGesture is broken
Problem LongPressGesture ignores minimumDuration parameter and succeeds immediately, also onEnded is never invoked. Steps to reproduce Take Apple’s own sample code from their documentation: LongPressGesture. Remove transaction.animation = Animation.easeIn(duration: 2.0) line to make the effect more obvious. Expected result: The circle must turn red after 3 seconds of pressing on it, and turn green when released. Actual result The circle turns red immediately and never turns green. Notes I tried many combinations of .gesture and .simultaneousGesture applied to different types of views. Was anyone able to make the minimum duration work when passed to .gesture modifier?
3
3
618
Mar ’24