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

Strange behaviour after modifying exposure duration and going back to AVCaptureExposureModeContinuousAutoExposure
When I set a custom exposure duration, like 1/8, and then switch back to continuous auto exposure, the exposure duration in areas that were previously 1/17 changes to something like 1/5 or 1/10. As a result, the screen becomes laggy and overexposed. I'm not sure why this is happening.
0
0
404
Sep ’24
How To Add Multiple Songs/Playlist to the Queue?
A couple of weeks ago I got help here to play one song and the solution to my problem was that I wasn't adding the song (Track Type) to the queue correctly, so now I want to be able to add a playlist worth of songs to the queue. The problem is when I try to add an array of the Track type I get an error. The other part of this issue for me is how do I access an individual song off of the queue after I add it? I see I can do ApplicationMusicPlayer.shared.queue.currentItem but I think I'm missing/misunderstanding something here. Anyway's I'll post the code I have to show how I'm attempting to do this at this moment. In this scenario we're getting passed in a playlist from another view. import SwiftUI import MusicKit struct PlayBackView: View { @State var song: Track? @State private var songs: [Track] = [] @State var playlist: Playlist private let player = ApplicationMusicPlayer.shared VStack { // Album Cover HStack(spacing: 20) { if let artwork = player.queue.currentEntry?.artwork { ArtworkImage(artwork, height: 100) } else { Image(systemName: "music.note") .resizable() .frame(width: 100, height: 100) } VStack(alignment: .leading) { // Song Title Text(player.queue.currentEntry?.title ?? "Song Title Not Found") .font(.title) .fixedSize(horizontal: false, vertical: true) } } } .padding() .task { await loadTracks() // It's Here I thought I could do something like this player.queue = tracks // Since I can do this with one singular track player.queue = [song] do { try await player.queue.insert(songs, position: .afterCurrentEntry) } catch { print(error.localizedDescription) } } } @MainActor private func loadTracks() async { do { let detailedPlaylist = try await playlist.with([.tracks]) let tracks = detailedPlaylist.tracks ?? [] setTracks(tracks) } catch { print(error.localizedDescription) } } @MainActor private func setTracks(_ tracks: MusicItemCollection<Track>) { songs = Array(tracks) } }
1
0
615
Sep ’24
Failed to launch app in reasonable time Xcode 16
I've updated my computer to Sequoia 15, Xcode 16 and now no matter what I do, I am unable to work with Swift UI previews. I get this error each time I try to run the preview: Failed to launch app in reasonable time I have done: Uninstall/Re-install Xcode Deleted derived data Deleted the simulator data Used DevCleaner to remove all data related to Xcode Searched all websites about this issue. ( Non shown a good solution ) Write this question on here. If anyone has found a solution, please let me know how you fixed it.
15
20
6.1k
Jun ’25
iOS 18 SwiftUI navigation bar problem
Okay I know, fill a bug... but here is a super simple app that will demostrate that the navigation bar chnages from Dark scheme to light scheme when you tap back after it goes to the second view. import SwiftUI struct ContentView: View { var body: some View { NavigationStack { NavigationLink { Text("Tap back and notice the navigation title changes to black text instead of white") .toolbarBackground(.visible, for: .navigationBar) .toolbarBackground(Color.orange, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } label: { VStack { Text("First page is the sweetest") } .padding() } .navigationTitle("First Page") .toolbarBackground(.visible, for: .navigationBar) .toolbarBackground(Color.orange, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } } } #Preview { ContentView() }
6
9
4.6k
Feb ’25
SwiftUI @main Accessing UserDefaults Too Early Before applicationDidFinishLaunching
I'm working on a macOS and iOS app using SwiftUI. And received bug from very few user that they are being logged out, even tho they didn't. So i'm assuming issue is relevant to this forum post, and that the keychain data and user defaults aren't available very early on in an app's lifecycle (presumably from cold start). There is fix available for iOS but didn't find anything relevant to isProtectedDataAvailable for macOS. I'm accessing UserDefaults in my @main view's sub view. It seems that UserDefaults is accessed too early, before applicationDidFinishLaunching. And therefore, not getting user data on launch sometimes. This issue is very rare, i'm not able to reproduce this, but assuming this can be cause based on some form post, also because view's onAppear calls before applicationDidFinishLaunching.
3
0
483
Sep ’24
Black text on white button on iOS 18 Accented Home Screen Widget
Hi. I am making my widgets ready for iOS 18 accented Home Screen widgets. I am having issues setting the color of text to black. This is required as I have a white button with black text and black icon. I have tried manually, without using my Color, to set the text to .black or .white. It will always be white. When applying the accent, I can use the .widgetAccentedRenderingMode(.fullColor) to turn the icon black, but I cannot do this for the text. Button(intent: --intent--) { HStack(alignment: .center) { Text("Play") .font(.system(size: 12, weight: .bold)) .foregroundStyle(Color("buttonAccentColor")) // Problem here, this is forced to be white, I want it to be black Image("resume") .renderingMode(.template) .resizable() .widgetAccentedRenderingMode(.fullColor) // This works .aspectRatio(contentMode: .fit) .frame(width: 16, height: 16) .foregroundStyle(Color("buttonAccentColor")) } .padding(8) .padding(.horizontal, 8) } .buttonStyle(.plain) .background(Color("neutral100")) .clipShape(Capsule())
1
3
489
Oct ’24
[ERROR] Could not create a bookmark: NSError: Cocoa 4097 "connection to service named com.apple.FileProvider" when using PhotosPicker
Hi I am using PhotosPicker and SwiftData with iOS17.0. I released my own app using codes of two above. No problem came up right until I upgraded my iphone to iOS 18.0 17th of September 24. A single post pokes the similar problem. SwiftData and PhotosPikcer. He or She said it was about SwiftData Model Insert something. But, I was able to use other methods that use SwiftData, so insert Model setup isn't my problem. But when tapping a photo to get a photo from PhotosPicker makes the ui goes down, and navigate back. Weird. iIt doesnt crash but when I tap a photo, the debug message [ERROR] Could not create a bookmark: NSError: Cocoa 4097 "connection to service named com.apple.FileProvider" comes up and the view navigates back. The selecting a photo itself doesnt include any SwiftData related methods, it only does loadTransferable thing and shows the photo on the screen. I cannot understand it. it only happened when I upgraded to iOS 18.0. AND Then i debugged the prob with Xcode 16.0 nothing but the unexpected message appears and not many posts are up here or google. Can you help me? Things I tried: Check any use of the PhotosPickerItem anywhere else. -> No where. Use try await loadTransferable Changed the form of initiating PhotosPikcer View Debugging every line -> Nothing appeared. PhotosPicker(selection: $currentImage, matching: .images, photoLibrary: .shared()) { Text("") } .frame(height: 360) .photosPickerStyle(.inline) .photosPickerAccessoryVisibility(.hidden, edges: .bottom) .photosPickerDisabledCapabilities(.selectionActions) .onChange(of: currentImage) { _, newImage in // SomeLogic } .ignoresSafeArea(edges: .bottom) .transition(.move(edge: .bottom).combined(with: .opacity))
8
4
2.7k
Oct ’24
Unable to compile SwiftUI Charts on Xcode 16.1 Beta 2
Unable to compile app that imports Swift UI Charts SDK on Xcode Version 16.1 beta 2 (16B5014f) with error: 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. FB15161667
5
15
2.2k
Oct ’24
SwiftUI: .textSelection(.enabled) not working in List on iOS 18
In iOS 18, textSelection(_:) not working in List. So, I can't copy text. Works on iOS 17 and earlier. Is this a bug and is there any solution? // Not Work: iOS 18 struct ContentView: View { var body: some View { List { Text("Hello World") .textSelection(.enabled) } } } // Work: iOS 18 and earlier struct ContentView: View { var body: some View { Text("Hello World") .textSelection(.enabled) } }
4
4
852
Sep ’24
Considering Alternatives to SwiftUI for a Complex App
I am working on an application that has some complex navigation needs, and I'm considering abandoning SwiftUI, at least in a few core areas of the app. I found SwiftUI intuitive and useful for simple things like: Using a state to toggle the appearance or disappearance of an element Using state to alter the look of UI elements Watching the values of built-in interfaces like TextField or Slider Controlling out-of-the-box UI elements like NavigationSplitView But now I've got a UI that depends on a data model that can change at any time, and from that data I'll display lists of objects, and objects in detail, and all of this will be displayed according to a NavigationPath that depends on the data model's internal structure. This means that, for instance, I may be in the detail view of element X after having traveled to it from the detail view of element Y which was tapped in a list of XYZ, which was the result of tapping into part of the detail view of element W. This whole path could be invalidated by an update to the data model when it's received from the network. Furthermore, any element could have it's details changed, or be deleted, and I'd want the UI to reflect that right away if possible. For the navigation work, I'm still optimistic that custom edits to a NavigationPath could be the way to go. However, for propagating data updates around my app, I know @State, @Bindable, etc are intended to handle this kind of thing, but when I'm try to send these bindings through the circuitous path of views I mentioned above, and I run into any unexpected hiccup, it feels like I'm at a disadvantage when debugging because I'm relying on opaque SwiftUI Magic to handle things under the hood in a way I don't really understand. I could put more effort into learning how this works, and potentially come up against some platform limitations, bugs, or other dead-ends, or I could just use Pub/Sub and a network of custom queues/pipes, and send updates around my app the old fashioned way, but using primitives whose functions are clear to me. I've been using SwiftUI for about a year and it still trips me up, and I have watched a few WWDC talks on the topic. I'd appreciate any advice on this front from the frequenters of this forum. Thanks for reading my post.
3
0
618
Oct ’24
Using truncationMode
Hi, The example that Apple shows in link below doesn't show how truncationMode works, because the text get truncated anyway when its length it more than frame height so what's the use of truncationMode ? https://developer.apple.com/documentation/swiftui/view/truncationmode(_:) -- Kind Regards
1
0
292
Sep ’24
Buttons in NavigationBar
Hi Guys, I saw in iOS 18 (Photos App) that there are buttons (in an scrollview) below the navigation title and inside the navigation bar. Is there an new API or an method to "clone" this UI without using: .safeAreaInset(edge: .top, content: { }) Thanks in advance for any feedback and help!
0
0
409
Sep ’24
Getting different StoreKit results between SandBox and StoreKitTransactions in Xcode
I’m using ‘Offer Codes’ in App Store Connect for subscriptions. I’m also using a StoreKit implementation that uses the subscriptionStatusTask modifier to assess if the user is subscribed or not. The part I’m not sure of is whether or not the subscriptionStatusTask modifier will recognize the status if the user has used an offer code. I think it should, as that modifier checks for currentEntitlements, and returns appropriately. I’ve been trying to test this out with the StoreKitTransactions system in Xcode, as SandBox does not currently support this. From what I can tell, this way does in fact seem to allow the user to access the app with an offer code. The app does not present the StoreKit view. However, when I’ve tried this with an actual user on the app store (aren’t mom’s great?), the offer code does not take, and they are presented with that StoreKit view. Not great. So can someone please shed some light on this? Is my understanding correct here? What else do I need to do?
0
0
438
Sep ’24
Request .full contacts authorization after being granted .limited
We're adjusting to the new iOS 18 .limited contacts access mode. In our app, we don't request contacts right away. We have a search bar where users can search through their own contacts and select one using the ContactAccessButton. If they do select one, then they're prompted to "Grant Limited Access", not "Grant Full Access", as the screenshot shows below. Later on, we want to offer the ability for users to sync their entire contact book with our app. This will improve their experience on the app by automatically finding all their friends already on the app, without them having to do the manual work of clicking on every single contact in the ContactsAccessPicker. Is this possible right now? It doesn't seem like it—when I call ContactsStore.requestAccess(for: .contacts) while in .limited access mode, nothing happens. But I would like to show a prompt that gives the user the ability to grant all their contacts to improve their experience.
1
0
635
Sep ’24
Xcode 16 SwiftUI List Fast Scrolling Issue
Hi! When building my app using Xcode 16, fast scrolling (using scrollViewProxy.scrollTo) a list would result in items not appearing even when scrolling stopped. This does not happen when the app is built with Xcode 15, even on iOS 18. I'm also getting this error in the logs: List failed to visit cell content, returning an empty cell. - SwiftUICore/Logging.swift:84 - please file a bug report.
5
6
1.3k
May ’25
How do you let SwiftUI View know that ViewModel's computed property has changed?
Imagine you have ViewModel which computed property may change from time to time: import Foundation class ViewModel: ObservableObject { private var val = 42; var compProp: Int { return val } func maybeChange() { if (Int.random(in: 0..<2) == 1) { val += 1 ??? //heyViewThePropertyIsChanged(nameof(compProp)) } } } How could you force the View: import SwiftUI struct ContentView: View { @StateObject var viewModel: ViewModel var body: some View { VStack { Text("\(viewModel.compProp)").font(.title) } .frame(minWidth: 320) .toolbar { Button(action: viewModel.maybeChange) { Label("Maybe", systemImage: "gear.badge.questionmark") } }.padding() } } to reflect such a change?
3
0
378
Sep ’24
Swift Charts - weak scrolling performance
Hello there! I wanted to give a native scrolling mechanism for the Swift Charts Graph a try and experiment a bit if the scenario that we try to achieve might be possible, but it seems that the Swift Charts scrolling performance is very poor. The graph was created as follows: X-axis is created based on a date range, Y-axis is created based on an integer values between moreless 0-320 value. the graph is scrollable horizontally only (x-axis), The time range (x-axis) for the scrolling content was set to one year from now date (so the user can scroll one year into the past as a minimum visible date (.chartXScale). The X-axis shows 3 hours of data per screen width (.chartXVisibleDomain). The data points for the graph are generated once when screen is about to appear so that the Charts engine can use it (no lazy loading implemented yet). The line data points (LineMark views) consist of 2880 data points distributed every 5 minutes which simulates - two days of continuous data stream that we want to present. The rest of the graph displays no data at all. The performance result: The graph on the initial loading phase is frozen for about 10-15 seconds until the data appears on the graph. Scrolling is very laggy - the CPU usage is 100% and is unacceptable for the end users. If we show no data at all on the graph (so no LineMark views are created at all) - the result is similar - the empty graph scrolling is also very laggy. Below I am sharing a test code: @main struct ChartsTestApp: App { var body: some Scene { WindowGroup { ContentView() Spacer() } } } struct LineDataPoint: Identifiable, Equatable { var id: Int let date: Date let value: Int } actor TestData { func generate(startDate: Date) async -> [LineDataPoint] { var values: [LineDataPoint] = [] for i in 0..<(1440 * 2) { values.append( LineDataPoint( id: i, date: startDate.addingTimeInterval( TimeInterval(60 * 5 * i) // Every 5 minutes ), value: Int.random(in: 1...100) ) ) } return values } } struct ContentView: View { var startDate: Date { return endDate.addingTimeInterval(-3600*24*30*12) // one year into the past from now } let endDate = Date() @State var dataPoints: [LineDataPoint] = [] var body: some View { Chart { ForEach(dataPoints) { item in LineMark( x: .value("Date", item.date), y: .value("Value", item.value), series: .value("Series", "Test") ) } } .frame(height: 200) .chartScrollableAxes(.horizontal) .chartYAxis(.hidden) .chartXScale(domain: startDate...endDate) // one year possibility to scroll back .chartXVisibleDomain(length: 3600 * 3) // 3 hours visible on screen .onAppear { Task { dataPoints = await TestData().generate(startDate: startDate) } } } } I would be grateful for any insights or suggestions on how to improve it or if it's planned to be improved in the future. Currently, I use UIKit CollectionView where we split the graph into smaller chunks of the graph and we present the SwiftUI Chart content in the cells, so we use the scrolling offered there. I wonder if it's possible to use native SwiftUI for such a scenario so that later on we could also implement some kind of lazy loading of the data as the user scrolls into the past.
3
2
952
Jun ’25
[NetworkComponent] Cannot find component's entity (guid=***, typeID=***, type=CustomComponentRCPInputTargetComponent, entity=xxxx).
Hi. I recently added SwiftUI context menus and picker menus to my app, but when they are activated they flicker rapidly, and it is impossible to select anything (there is no hover effect either). When these menus are activated, the console prints lots of warning messages similar to this: [NetworkComponent] Cannot find component's entity (guid=14395713952467043328, typeID=295756909031380028, type=CustomComponentRCPInputTargetComponent, entity=0x1047c6750). This issue doesn't seem to happen on visionOS 1.2 simulator, but is reliably reproducible on visionOS 2.0 simulator and device. Any idea what this might be related to? I am attempting to narrow down on the issue but it's challenging to do so without knowing what the error is about. Thanks!
1
0
567
Sep ’24