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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

contextMenu and right click
Hi, I made a "Finder view" with SwiftUI, how is it possible to call viewModel.selectFileWithAnimation(file) when .contextMenu show? Thank you! @StateObject private var viewModel = FilesViewModel() // Use the view model to manage data and logic var body: some View { VStack { // Horizontal scrolling of files and folders ScrollView(.horizontal, showsIndicators: false) { if viewModel.sortedAndFilteredFolderContents.isEmpty { // Show "No Results" if no files or folders found Text("No Results") .font(.headline) .foregroundColor(.almostWhite) .padding() } else { HStack(spacing: 20) { ForEach(viewModel.sortedAndFilteredFolderContents, id: \.self) { file in VStack { ZStack { // Selection effect without matchedGeometryEffect if viewModel.selectedFile == file { RoundedRectangle(cornerRadius: 10) .fill(Color.blue.opacity(0.2)) .transition(.opacity) .frame(width: 80, height: 100) .animation(.easeInOut(duration: 0.3), value: viewModel.selectedFile) } VStack { Image(nsImage: viewModel.getFileIcon(for: file)) .resizable() .frame(width: 64, height: 64) .onTapGesture(count: 2) { // Select and open file/folder on double-tap viewModel.selectFileWithAnimation(file) viewModel.openFileOrFolder(file) } .onTapGesture { viewModel.selectFileWithAnimation(file) } .onLongPressGesture(minimumDuration: 0.5) { // Rename file with long press viewModel.rename(file) } .contextMenu { // Define your context menu buttons here Button(action: { viewModel.showInFinder(file) }) { Text("Show in Finder") Image(systemName: "folder") } Button(action: { viewModel.moveToTrash(file) }) { Text("Move to Trash") Image(systemName: "trash") } Button(action: { viewModel.rename(file) }) { Text("Rename") Image(systemName: "pencil") } Button(action: { viewModel.makeAlias(for: file) }) { Text("Make Alias") Image(systemName: "link") } Button(action: { viewModel.compress(file) }) { Text("Compress \(file.lastPathComponent)") Image(systemName: "archivebox") } Button(action: { viewModel.copyFile(file) }) { Text("Copy") Image(systemName: "doc.on.doc") } Button(action: { viewModel.shareFile(file, in: dynaClip.view) }) { Text("Share") Image(systemName: "square.and.arrow.up") } } Text(file.lastPathComponent) .font(.caption) .lineLimit(1) .truncationMode(.tail) .frame(width: 80) } } } } } .padding(.top, 20) } }
1
0
165
3w
How to make an updatable ForEach loop SwiftUI
I have a ForEach loop in my code which is used to display text per child of an array (i think it's an array). var flags: [String: Any] = [ "Flag1": "FlagValue" // More values will go here, by default there are no values (but can be // loaded in) ] And this is my code // CONTENT HStack { VStack { ForEach(0...flags.count, id: \.self) { flag in Text("hey") } } } When I start the app there's only one "hey" and no more will show up when I add more flags.
10
0
244
3w
AsyncImage returning Unknown Context error
Hello. On Xcode 15 I am trying to use AsyncImage to display an image from a URL. Whey I try, I get this in error: The operation couldn't be completed. (SwiftUI.AsyncImage<SwiftUI._ConditionalContent <SwiftUl._ConditionalContent<SwiftUI.Text, SwiftUI.Text>, SwiftUI._ConditionalContent<SwiftUI.Text, SwiftUI.Text>>>.(unknown context at $1c552a084).LoadingError error 1.) The view is simple, a VStack containing the AsyncImage call with a known good URL: import SwiftUI struct SetRowView: View { var set: MagicSet var body: some View { VStack { AsyncImage(url: URL(string: set.icon_svg_uri)) { phase in if let image = phase.image { image } else if phase.error != nil { Text(phase.error!.localizedDescription.debugDescription) } } } } } I've even hard-coded the URL to the image I want to load. Same result. I can't find any reference to this error at all.
0
0
114
3w
LazyVGrid and multi item drag
The List control allows for multi selection and works seamlessly to select multiple items fro draggable. This does not work with LazyVGrid. I can only get a single item to drag. Tapping another item does not add to the drag collection. Is this not supported? You can see this work just fine in the Photos app. You can drag an item and easily add additional by tapping another while dragging. Just want this behavior in SwiftUI
3
0
218
3w
draggable modifier and Updatable Preview View
I am having to do some custom drag and drop with the draggable modifier and I am using a Preview, but I can't get the preview to update when there are more items being dragged. The original Preview remains static. Is this not possible to update a View that is being dragged?
2
0
196
3w
SwiftUI font size layout bug
This is an example of the view that has a glitch in layout. struct SomeSection: View { var body: some View { ZStack(alignment: .topTrailing) { VStack(spacing: 16) { Text("This is title\n with two lines") .font(.system(size: 24).bold()) .multilineTextAlignment(.center) Text("This is long description text\n that occupies more than 2 lines \n and in that case it causes a bug") .font(.system(size: 15)) .multilineTextAlignment(.center) } .background(Color.orange) Button { print("close") } label: { Image(systemName: "xmark") } .background(.green) } .background(.red) } } You can see red bar at the bottom that should not be visible. Top multilined label doesn't occupy necessary space and is trimmed. But if you change size of top label's font to 22 or LESS OR bottom label's font to 16 or MORE everything will look accordingly expectations. Can anyone explain why this happens and how to fix it?
0
0
145
3w
How to remove a second search text on tvOS18?
I have an issue on tvOS 18 beta from Aug 20, where the search text is displayed twice, as in the image below. Code to reproduce the behavior is trivial: struct ContentView: View { @State private var searchText = "" var body: some View { NavigationView { Text("Some content...") } .searchable(text: $searchText) } } I did not find anything new in the API or documentation to disable it. Also, online searches for this specific issue did not produce any results. I would like to show the same behavior on tvOS18, as on tvOS17, without the second search text. Any idea on how to hide that second search text?
1
0
223
3w
How to create a custom TimeDataSource?
Hello. I am working with the iOS 18b8 and Xcode 16b6 betas, updating a Live Activity Widget to adopt the new FormatStyle variants of the SwiftUI Text views. We used to use: Text(workoutStartDate, style: .relative) and it seems with iOS 18 we can replace it with: Text(workoutStartDate, format: .relative(presentation: .numeric, unitsStyle: .wide)) The former code would auto-increment, allowing a user to look at their Live Activity and see the duration of their workout so far ticking by. The new code does provide a nice relative duration string, but it doesn't auto-increment in the Live Activity's View – I need that functionality. I also updated other Texts in the Live Activity's View to adopt the .timer and .stopwatch FormatStyles. Those auto-increment and update no problem – once I realized I needed to provide a TimeDataSource<Date>.currentDate and not a simple Date. But in this .relative case, there is no auto-incrementing, and I'm guessing it may be due to providing a Date (workoutStartDate) and not a TimeDataSource<Date> as TimeDataSource seems to be the magic to make the Text auto-increment (or it's possible this format simply doesn't support auto-increment? bummer if so since the prior way did). How can I have a TimeDataSource<Date> that vends my arbitrary date (workoutStartDate)? I dug around, didn't find anything, but I wouldn't be surprised if I was overlooking something. PS: I have tried other approaches to solve this, such as simply using a .timer or .stopwatch format. That would change the under experience under iOS 18, and we think degrade it (the relative textual representation is nicer and provides distinction from the .timer also in the same View). We could keep the former approach, despite the minor layout issues under iOS 18. I have considered additional approaches as well – and am totally open to more! Here tho, I am truly curious how one might provide a custom TimeDataSource anchored at a date we provide (perhaps dynamically). Thank you.
0
1
211
3w
Get Home Screen tint color
Is there a way to read the Home Screen tint color. The @Environment(.\colorScheme) is only giving access to .light &amp; .dark. Is there another environment option that has access to the tinted color the user has selected for their Home Screen?
0
0
150
3w
Customising TabView styling
The default design of TabView is 90% close to what I want. However, the icons, to my eye, lack a sufficient amount of spacing at the top, and slightly too much white space at the bottom. Is there a way to give more top padding to the icons? To move the icons down without changing the height of the TabView itself? Also, I find it weird that .labelStyle(.titleOnly) works on Tabs but .labelStyle(.iconOnly) doesn't work. Is that a bug? I had to use Image instead of Label: TabView { Tab { MailView() } label: { Image(systemName: "envelope") .padding(20) } Tab { SettingsView() } label: { Image(systemName: "gearshape") .padding(20) } }
2
0
165
3w
Updating control widget with push notification data
I have been trying to add a control widget to my app. Now I want to show some info on control widget that is received from push notification data. In the apple documentation, they have added a push notification handler, but the pushTokensDidChange method only has the information of the controls whose push tokens are changed. There is no information on where can I access the push notification data and how to use the push notification data to update the info being shown in the control widget.
1
0
145
4w
preferredColorScheme Broken in iOS 18
iOS 18 seems to have broken preferredColorScheme. With the device in light mode, we first set preferredColorScheme as .dark, then we switch it to .none. The expected behaviour would be for the UI to switch from dark mode to light mode, which is what happens in previous versions. However, on iOS 18, it stays in dark mode until the app is reopened.
3
2
246
4w
[iOS 18] Colors from asset catalog render as pure white on tinted widgets
When a widget uses a custom color from Assets catalog. Those colors seem to be ignored and rendered as pure white when used in a widget and the Home Screen is set into the Tinted mode. This can be re-produced both in a Simulator and on a device and on the latest 18.1 beta (as of writing this post). Occasionally, I was able to catch the widget to be rendered correctly after it had been on the Home Screen for some time, but I could not identify what caused it, just re-rendering the widget by pushing a new entry into the timeline or changing the configuration, does not help the issue, colors are still rendered white. I've attached the screenshots with my widget rendered in tree different modes. Has anyone also encountered this? I'm not sure if I need to do something extra to properly support tinted mode.
1
0
362
4w
Trouble using more than one color with SF Symbols in tinted mode
When a widget is using the new tinted mode in iOS 18 the Weather app shows the SF Symbols in both white and the tint color. For example, a tinted sun with a white arrow for sunrise. I can't figure out how to do this. If I add widgetAccentable to the Image(systemName:) the entire Image becomes the tint color. If I don't use it no combination of rendering mode or foreground style makes the tint color appear. I can't find any mention of this in the WWDC sessions.
1
0
197
4w
Tapping tab icon causes incorrect navigation title layout in SwiftUI on iOS 18
Hello, I'm so glad that now you can scroll the list to top by tapping the tab bar ion on iOS 18. However, the current implementation on iOS 18 beta 8 has a little layout issue. import SwiftUI struct ContentView: View { var body: some View { TabView { Tab("Home", systemImage: "house") { NavigationStack { List { ForEach(0..<100) { i in Text("\(i)") } } .navigationTitle("Root") } } } } } #Preview { ContentView() } Tap the tab icon: Result:
2
0
213
4w
SwiftUI Picker not trigger `onChange` first time when inside Menu in MacOS
code import SwiftUI @main struct swiftuiTestApp: App { @State private var value = "a"; var body: some Scene { WindowGroup { Menu("menu") { Picker("", selection: $value) { Text("A").tag("a") Text("B").tag("b") Text("C").tag("c") } .pickerStyle(.inline) .onChange(of: value) { oldValue, newValue in print("onChange", newValue) } } } } } on MacOS, onChange is not triggered when an option is selected for the first time, but subsequent option selections are triggered。 on MacOS, when Picker is not inside Menu, it works fine on iOS, both works fine with inside or not inside menu
6
0
266
4w
ScrollViewProxy scrollTo in onAppear may cause state changes to be lost
Scrolling to a SwiftUI view with the onAppear method can cause state changes of published values from an ObservableObject to be lost and a view to be displayed in an incorrect state. Here is a demo showing the problem: struct ContentView: View { @StateObject private var viewModel = ContentViewModel() @Namespace private var state2ID var body: some View { ScrollViewReader { scrollProxy in ScrollView(.vertical) { VStack(spacing: 15) { if viewModel.state2 { VStack { Text("State2 is set") } .id(state2ID) .onAppear { print("scrolling") withAnimation { scrollProxy.scrollTo(state2ID) } } } VStack(spacing: 0) { Text("State1: \(viewModel.state1)") Text("State1 changes from 'false -> true -> false' when the button is pressed.") .font(.footnote) } Button("Toggle States") { viewModel.toggleStates() } .buttonStyle(.bordered) Color.teal .frame(height: 900) } .padding() } } } } @MainActor final class ContentViewModel: ObservableObject { @Published private(set) var state1 = false @Published private(set) var state2 = false private var stateToggle = false func toggleStates() { Task { @MainActor in state1 = true defer { // This change never becomes visible in the view! // state1 will be improperly shown as 'true' when this method returns while it actually is 'false'. print("Resetting state1") state1 = false } stateToggle.toggle() if stateToggle { withAnimation { state2 = true } } else { state2 = false } } } } After pressing the button, “State1: true” is displayed in the view, which no longer corresponds to the actual value of the view model property, which is false. Effectively, the change in the defer call of the toggleStates method is lost and the view is no longer in sync with the actual state values of the view model. Tested with iOS 17.5 and 18.0 (devices + simulators)
1
0
187
4w
colorScheme value always dark after setting dark mode in display and brightness even if Home Screen customization is light
If you set the display and brightness settings in iOS to be in dark mode, then the value returned in the colorScheme environment value: https://developer.apple.com/documentation/swiftui/environmentvalues/colorscheme @Environment(.colorScheme) var colorScheme is always dark, even if you toggle between light or dark in the Home Screen customization option. Tinted is reported correctly. Is there some way to get the Home Screen customization light/dark/tinted value correctly? Swapping the Home Screen customization value between light/dark does swap between the light and dark app icon so it seems like the widget color scheme should also swap in this case.
1
0
212
4w
searchable: Add an auxilliary search view
Is there a clean way to add an auxilliary view to the SwiftUI .searchable view? The best I have found is to add a VStack above the list being searched, but this makes the removal transition behave funny. ("Funny" means the search view and aux views animate away fine, but after they finish animating the List view snaps to the top of the screen, hiding the idle search field. The normal behavior leaves the idle search field showing.) NavigationStack { MyListView().searchable(...) } ——— struct MyListView: View { @Environment(\.isSearching) private var isSearching var body: some View { if isSearching { VStack {...my auxilliary view...} } List {...} } }
3
0
168
Sep ’24