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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Getting inconsistent padding on widgets between devices and simulators
I'm trying to design a homescreen widget but I am unable to properly control the padding and sizing of various components. In the four attached screenshots you can see the huge variation in padding around the outside, the change in text colour and the spacing between the text. I've boiled it down as simple as possible and attached the view as a sample file. What I'd like to achieve is a consistent look between iPads and iPhones and ideally in the simulator too. Is there a simple way to set the padding so that all places use the same, and then scale the text so that I know that if the text fits in the simulator the same text will fit on all devices? Device iPad 8 - 17.7 iPhone 13 Pro Max - 17.7 Xcode Canvas - iPad 13" Simulator - iPad Pro sampleview.txt 13"
0
0
107
2w
SwiftUI List hidden line separator not working
Hi, I have the below code as you can see the list doesn't hide its line separator, so is it a bug ? is there any work around ? @State var flag: Bool = false var myList: [String] = ["Hello", "World", "SwiftUI"] var body: some View { VStack(alignment: .leading) { List (myList, id: \.self) { list in Text(list) } .listRowSeparator(.hidden) .listStyle(.plain) } .overlay( RoundedRectangle(cornerRadius: 10) .stroke(sysSecondary.opacity(0.4), lineWidth: 1) ) .frame(width: 220, height:260) .background(.white) .clipShape (RoundedRectangle (cornerRadius: 10)) } }
1
0
133
2w
minimumScaleFactor for Text in widgets scales the text.
Hi, In my widgets, I use minimumScaleFactor to ensure that my text is readable. In iOS 18.0 beta 6 and iOS18.0 beta 7, my texts suddenly became very small. It seems that minimumScaleFactor acts like if it was applying the given scale value to the text. minimumScaleFactor(0.1) seems to display the text 90% smaller than the text without calling minimumScaleFactor. minimumScaleFactor(0.5) seems to display the text 50% smaller than the text without calling minimumScaleFactor. Is this a bug, of is there an unexpected change in the API ? Edit : I have created FB14890220, in case this message remains unseen.
8
2
591
Aug ’24
Live queries on SwiftData DB but without @Query macro?
I switched from using @Query to @ModelActor because of the following reasons: Performance Issues: With @Query, my app became unresponsive with large datasets because data fetching occurred on the main thread. Integration with CKSyncEngine: I needed to implement @ModelActor anyway to allow CKSyncEngine to add data to local persistent storage from the background. In my current setup, the onAppear() method for my view calls the getItems() function on my model actor, which returns [ItemsDTO] and then View renders them. However, I'm now facing a challenge in achieving the same automatic data refreshing and view updates that @Query provided. Here are a few potential solutions I'm considering: Periodic Data Fetching: Fetch data at regular intervals to keep the view updated. But this seems expensive. Local Write Monitoring: Monitor all local writes to automatically trigger updates when changes occur. But this is quite a lot of code I would have to write myself. Switch to manual refresh: Users would have to manually trigger UI updates by pressing button. Reintroduce @Query: Writes would happen from ModelActor, but reads would still happen from Main thread. But then again app would become unresponsive on reads. If you have any additional ideas or best practices for maintaining reactivity with @ModelActor, I'd love to hear them!
1
0
270
2w
Open an specific view or sheet of the app from a control widget button
Hi everyone. I'm trying to use the new ControlWidget API introduced on iOS 18 to open a sheet that contains a form when the user taps on the button on the control center. This is my current code. It opens the app, but I haven't found how to do an action inside the app when the app is opened. @available(iOS 18, *) struct AddButtonWidgetControl: ControlWidget { var body: some ControlWidgetConfiguration { StaticControlConfiguration(kind: "com.example.myapp.ButtonWidget") { ControlWidgetButton(action: LaunchAppIntent()) { Label("Add a link", systemImage: "plus") } } .displayName("Add a link") .description("Creates a link.") } } @available(iOS 18, *) struct LaunchAppIntent: AppIntent { static var title: LocalizedStringResource { "Launch app" } static var openAppWhenRun: Bool = true func perform() async throws -> some IntentResult { return .result() } }
2
0
220
2w
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
3
13
996
2w
[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))
3
2
288
2w
AppIntent - Widget & ControlWidget
Hey all, iOS 18 - RC I have an app that supports both Widgets and ControlWidget, which resides on the same AppIntent. The following sync works fine when any action is taken on any of the three players - App - Widget - both directions - works as expected App - Control Widget - both directions - works as expected However - Widget - ControlWidget - the UI not always sync in real time (the values are ok) So if for instance I increase a counter on the widget from 1 to 2, the comtrolwidget will still show 1, but if I tap it, it will increase to 3. For any update/action taken on the AppInten, I call - WidgetCenter.shared.reloadAllTimelines() ControlCenter.shared.reloadAllControls() Any idea how to ensure this sync? Thanks a lot! Dudi
1
0
251
3w
Obtaining the RGB values for a color in darkMode
I have a colorSet which includes a "Any Appearance" color and a "Dark" color. I have a need to get the hex value of both. I know how to add a .colorScheme(.dark) view modifier to cause the view to adapt to darkMode. That is not the issue. I want to display a swatch containing the darkMode color and I want to display the hex value under the swatch. No matter what I do, it always returns the hex value of the "Any Appearance" version of the color. It seems that the solution might be to use Color.resolve(in:EnvironmentValues), but I do not see how to specify the needed EnvironmentValues
1
0
122
2w
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
122
2w
Frequent Crash on Table Content Change
One of my apps has been crashing on multiple Sequoia betas, something that never happened on prior macOS versions, and I’ve finally narrowed it down to a smaller reproducible case which I've attached to bug report #FB14473269. The narrowed case is fairly trivial. A table containing data is filtered by typing into a text field which narrows the bound content by finding only text with matching substrings. It's a single basic view the source for which is included in its entirety below. To reproduce the crash: Compile and run Type “five” in the search text If this doesn’t immediately crash it with the first keystroke (there seems to be some kind of race condition so it may vary on different hardware configurations), delete a character at a time and repeat as necessary. Typing “one” on my system doesn’t crash the app, but deleting backwards to just “o” immediately crashes. The backtrace is entirely within SwiftUI. This works flawlessly on Sonoma which is where I've been building and testing the app where this problem was first discovered, and it's completely unusable up through beta 5 of Sequoia. It's hard to believe nobody else is encountering this. Any suggestions? import SwiftUI class Item: Identifiable { var id: String init(_ id: String) { self.id = id } } struct ContentView: View { @State var allItems = [ Item("One"), Item("Two"), Item("Three"), Item("Four"), Item("Five"), Item("Six"), Item("Seven"), Item("Eight"), Item("Nine"), Item("Ten") ] @State var filteredItems = [Item]() @State var selectedItems = Set<Item.ID>() @State var text: String = "" func filter() { if text == "" { filteredItems = allItems } else { filteredItems = allItems.filter { $0.id.localizedCaseInsensitiveContains(text) } } } var body: some View { VStack { TextField("Search:", text: $text) .padding() .onChange(of: text) { filter() } .onAppear { filter() } Table($filteredItems, selection: $selectedItems) { TableColumn("Name") { item in Text(item.id) } } } } } #Preview { ContentView() }
8
1
384
Aug ’24
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
150
2w
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.
2
2
270
2w
Sonoma 14.4.1 macOS Menu Issues
Sonoma 14.4.1 (did not test on 14.4) Xcode 15.3 New Project macOS Document App Run View menu has "Enter Full Screen" Do Command-N View menu does not have "Enter Full Screen" May need to open and close a few windows. import SwiftUI @main struct testApp: App { var body: some Scene { DocumentGroup(newDocument: testDocument()) { file in ContentView(document: file.$document) } .commands { CommandGroup(replacing: CommandGroupPlacement.saveItem) { } } } } File menu Open Recent becomes NSMenuItem
3
0
440
Mar ’24
Lag When Dismissing Keyboard in ScrollView Inside NavigationStack in SwiftUI
I’m experiencing a lag in SwiftUI when dismissing the keyboard inside a ScrollView that’s within a NavigationStack. When the keyboard is opened and then dismissed, the view seems to lag as it resizes back to its original state. This issue occurs when the content is in a ScrollView. I’m using iOS 17, and the resizing of the content feels choppy after the keyboard interaction. Here’s a simplified version of my code: VStack { NavigationStack { ScrollView { createAllForm } .onAppear { if #available(iOS 17.0, *) { Self.addTripOpen.sendDonation() } } .toolbar { ToolbarItem(placement: .topBarLeading) { Button(action: { presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: IconsEnum.closeIcon).foregroundColor(.gray) }) } } .toolbar { ToolbarItem(placement: .topBarTrailing) { Button(LocalizedText.create, action: { focusedField = nil withAnimation { addTripViewModel.creatingTrip = true addTripViewModel.addTripToFirebase(presentationMode: presentationMode) } }).disabled(addTripViewModel.disableCreate).foregroundColor(Color(addTripViewModel.disableCreate ? ColorsEnum.greyColor : ColorsEnum.tripBlue)) } } .navigationTitle(LocalizedText.createTrip) .navigationBarTitleDisplayMode(.inline) .isLoadingView(isLoading: addTripViewModel.creatingTrip) .alert(addTripViewModel.alertMessage, isPresented: $addTripViewModel.showingAlert) { Button(LocalizedText.acceptLabel, role: .cancel) { } } .onDisappear { if addTripViewModel.isCreated { processCompletedCount += 1 } if let currentAppVersion = Bundle.currentAppVersion, processCompletedCount >= 2, currentAppVersion != lastVersionPromptedForReview, addTripViewModel.isCreated { presentReview() lastVersionPromptedForReview = currentAppVersion } onDismiss(addTripViewModel.isCreated) } .sheet(isPresented: $addTripViewModel.showingAddUsers) { AddUsers().environmentObject(addTripViewModel) } } }
2
0
122
3w
onScrollVisibilityChange for Lists
I cannot make the new onScrollVisibilityChange work within Lists. Is this an expected limitation or am I doing something wrong? Please see the sample code below. Thank you! struct TestView: View { @State var isTitleVisible: Bool = true var body: some View { List { Section { Text("Title") } .onScrollVisibilityChange { isVisible in self.isTitleVisible = isVisible } Section { ForEach((0..<100), id: \.self) { i in Text(i.formatted()) } /// Changes the background color from green to red once the title is no more visible .listRowBackground(isTitleVisible ? Color.green : .red) } } } }
2
0
152
3w