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

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

Accept a Review Rejection Defeat or Play Along with Reviewer
I have a desktop application developed in SwiftUI that shows property locations on the map. That's NOT the main feature. IF you give the application permission to access your location, the blue dot will appear on the map. If you don't, the blue user dot won't appear. That's the only difference with location services. In other words, the application has no use of user's current position beyond showing it on the map. Since it's just the matter of showing or not showing the blue dot on the map, the application doesn't really need to use the location service. Anyway, the reviewer is talking about something else by rejecting the application in two aspects. Guideline 5.1.1 - Legal - Privacy - Data Collection and Storage Guideline 5.1.5 - Legal - Privacy - Location Services As I said earlier, the application only wants to show the blue dot on the map so that you can see your property locations relative to your current location. In code, it's something like the following. Map(position: $propertyViewModel.mapPosition) { ForEach(propertyViewModel.properties) { property in Annotation("", coordinate: CLLocationCoordinate2D(latitude: property.lat, longitude: property.lon)) { ... } } UserAnnotation() } So I'm hit with two rejection reasons with this one line. UserAnnotation() And the reviewer is talking about something like the app is not functional when Location Services are disabled. To resolve this issue, please revise the app so that the app is fully functional without requiring the user to enable Location Services. Well, I can remove the UserAnnotation() line if I want to put this application through the review process. Nothing will become dysfunctional, though, if you decide to reject permission request. So would you remove it or would you play along with this reviewer if you were me? It's been three or four days since rejection. As you can imagine, the reviewer doesn't bother to answer as to What are the exact coordinates that the application has allegedly collected What won't work as a result of location permission request refusal. This isn't the first time I get my app rejected. I've probably had 150 to 200 of them rejected in the past 15 years. And just because a reviewer rejects your app for a bizarre reason, would you give in? Remove this feature and that feature because the reviewer is incompetent such that he or she makes his or her decision based on imagination? What do you think?
3
0
50
3m
How to accept CloudKit shares with the new SwiftUI app lifecycle?
In the iOS 13 world, I had code like this: class SceneDelegate: UIResponder, UIWindowSceneDelegate { 		func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) { 				// do stuff with the metadata, eventually call CKAcceptSharesOperation 		} } I am migrating my app to the new SwiftUI app lifecycle, and can’t figure out where to put this method. It used to live in AppDelegate pre-iOS13, and I tried going back to that, but the AppDelegate version never gets called. There doesn’t seem to be a SceneDelegateAdaptor akin to UIApplicationDelegateAdaptor available, which would provide a bridge to the old code. So, I’m lost. How do I accept CloudKit shares with SwiftUI app lifecycle? 🙈
4
0
1.3k
15m
NSTableView/NSScrollView jumping scroll position during NSSplitView resize
This is a very basic macOS Finder-style test app using AppKit. I am experiencing a "jump" in the vertical scroll position of my NSTableView (inside an NSScrollView) specifically when the window is resized horizontally. This happens when columns are visually added or removed. Framework: AppKit (Cocoa) Xcode/macOS: 26.2 Code: https://github.com/MorusPatre/Binder/blob/main/ContentView%20-%20Scroll%20Jump%20during%20Resize.swift
0
0
27
4h
How to animate `UIHostingController.view` frame when my View's size changes?
I have a UIHostingController on which I have set: hostingController.sizingOptions = [.intrinsicContentSize] The size of my SwiftUI content changes with animation (I update a @Published property on an ObservableObject inside a withAnimation block). However, I notice that my hostingController.view just jumps to the new frame without animating the change. Question: how can I animate the frame changes in UIHostingController that are caused by sizingOptions = [.intrinsicContentSize]
6
1
267
5h
Image not rendering on some devices
Hi, new developer here. I have an issue where an image I have on app is not showing up on some devices. The image is: Resources/Assets/logo: I am using it in my app like: ZStack { Color.white .ignoresSafeArea() VStack { Spacer() Image("logo") Spacer() Text(dateString) .font(.custom("LinLibertine", size: 17)) .fontWeight(.bold) .tracking(5) .padding(.bottom, 50) } } The image appears fine on all simulators. And also on my real device iPad with A14. But when I run it on iPhone 8 or iPad Air M4, it shows empty space in place of image. I tried many different options like: Image("logo") .renderingMode(.original) .resizable() .scaledToFit() frame(width: 300) .background(Color.red.opacity(0.3)) But nothing works. What can be the issue?
1
1
94
12h
Can I disable a SwiftUI View from being a draggable source, but still leave it enabled as a dropDestination?
My app has a collection of Cell Views. some of the views' model objects include a Player, and others do not. I want to use drag and drop to move a player from one cell to another. I only want cells that contain a player to be valid drag sources. All cells will be valid drop destinations. When I uncomment the .disabled line both drag and drop become disabled. Is it possible to keep a view enabled as a dropDestination but disabled as a draggable source? VStack { Image("playerJersey_red") if let player = content.player { Text(player.name) } } .draggable(content) // .disabled(content.player == nil) .dropDestination(for: CellContent.self) { items, location in One thing I tried was to wrap everything in a ZStack and put a rectangle with .opacity(0.02) above the Image/Text VStack. I then left draggable modifying my VStack and moved dropDestination to the clear rectangle. This didn't work as I wasn't able to initiate a drag when tapping on the rectangle. Any other ideas or suggestions? thanks
4
0
168
16h
Wrong position of searchable component on first render
Hey all, I found a weird behaviour with the searchable component. I created a custom bottom nav bar (because I have custom design in my app) to switch between screens. On one screen I display a List component with the searchable component. Whenever I enter the search screen the first time, the searchable component is displayed at the bottom. This is wrong. It should be displayed at the top under the navigationTitle. When I enter the screen a second time, everything is correct. This behaviour can be reproduced on all iOS 26 versions on the simulator and on a physical device with debug and release build. On iOS 18 everything works fine. Steps to reproduce: Cold start of the app Click on Search TabBarIcon (searchable wrong location) Click on Home TabBarIcon Click on Search TabBarIcon (searchable correct location) Simple code example: import SwiftUI struct ContentView: View { @State var selectedTab: Page = Page.main var body: some View { NavigationStack { ZStack { VStack { switch selectedTab { case .main: MainView() case .search: SearchView() } } VStack { Spacer() VStack(spacing: 0) { HStack(spacing: 0) { TabBarIcon(iconName: "house", selected: selectedTab == .main, displayName: "Home") .onTapGesture { selectedTab = .main } TabBarIcon(iconName: "magnifyingglass", selected: selectedTab == .search, displayName: "Search") .onTapGesture { selectedTab = .search } } .frame(maxWidth: .infinity) .frame(height: 55) .background(Color.gray) } .ignoresSafeArea(.all, edges: .bottom) } } } } } struct TabBarIcon: View { let iconName: String let selected: Bool let displayName: String var body: some View { ZStack { VStack { Image(systemName: iconName) .resizable() .renderingMode(.template) .aspectRatio(contentMode: .fit) .foregroundColor(Color.black) .frame(width: 22, height: 22) Text(displayName) .font(Font.system(size: 10)) } } .frame(maxWidth: .infinity) } } enum Page { case main case search } struct MainView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .navigationTitle("Home") } } struct SearchView: View { @State private var searchText = "" let items = [ "Apple", "Banana", "Pear", "Strawberry", "Orange", "Peach", "Grape", "Mango" ] var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.localizedCaseInsensitiveContains(searchText) } } } var body: some View { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") } }
1
0
85
19h
Help with visionOS pushWindow issues requested
I first started using the SwiftUI pushWindow API in visionOS 26.2, and I've reported several bugs I discovered, listed below. Under certain circumstances, pushed window relationships may break, and this behavior affects all other apps, not just the app that caused the problem, until the next device reboot. In other cases, the system may crash and restart. (FB21287011) When a window presented with pushWindow is dismissed, its parent window reappears in the wrong location (FB21294645) Pinning a pushed window to a wall breaks pushWindow for all other apps on the system (FB21594646) pushWindow interacts poorly with the window bar close app option (FB21652261) If a window locked to a wall calls pushWindow, the original window becomes unlocked (FB21652271) If a window locked in place calls pushWindow and the pushed window is closed, the system freezes (FB21828413) pushWindow, UIApplication.open, and a dismissed immersive space result in multiple failures that require a device reboot (FB21840747) visionOS randomly foregrounds a backgrounded immersive space app with a pushed window's parent window visible instead of the pushed window (FB21864652) When a running app is selected in the visionOS home view, windows presented with pushWindow spontaneously close (FB21873482) Pushed windows use the fixed scaling behavior instead of the dynamic scaling behavior I'm posting the issues here in case this information is helpful to other developers. I'd also like to hear about other pushWindow issues developers have encountered, so I can watch out for them. Questions: I've discovered that some of the issues above can be partially worked around by applying the defaultLaunchBehavior and restorationBehavior scene modifiers to suppress window restoration and locking, which pushWindow appears to interact poorly with. Are there other recommended workarounds? I've observed that the Photos and Settings apps, which predate the pushWindow API, are not affected by the issues I reported. Are there other more reliable ways I could achieve the same behavior as pushWindow without relying on that API? I'd appreciate any guidance Apple engineers could provide. Thank you.
0
2
69
20h
Severe Frame Drops When Resizing macOS Window with Dynamic LazyVGrid
Context: I am building a macOS file (currently image only) browser using SwiftUI. The core view is a ScrollView containing a LazyVGrid. The layout is dynamic: as the window resizes, I calculate the optimal number of columns and spacing using a GeometryReader. The Issue: While scrolling is pretty smooth (thanks to custom image caching and prefetching), window resizing is significantly laggy. After having scrolled the UI stutters and drops frames heavily while dragging the window edge. The Code: https://github.com/MorusPatre/Binder
1
0
58
20h
Conditional Modifiers *if available*
I am adopting some of the new glass UI, but having to duplicate a lot of code to maintain support for previous UI systems in macOS. An example: if #available(macOS 26.0, *) { VStack { /*some 40+ lines of code clipped here for brevity*/ } .cueButtons() .cueStyleGlass() } else { VStack { /*identical 40+ lines of code clipped here for brevity*/ } .cueButtons() .cueStyle() } If I try to use conditional modifiers as indicated here: extension View { func cueStyle(font: Font = .system(size: 45)) -> some View { if #available(macOS 26.0, *) { modifier(GlassCueStyle(font: font)) } else { modifier(CueStyle(font: font)) } } } I get this error: Conflicting arguments to generic parameter 'τ_1_0' ('ModifiedContent<Self, GlassCueStyle>' vs. 'ModifiedContent<Self, CueStyle>') Is there a better way to do this?
3
0
203
21h
Changing focus state in onSubmit causes keyboard to bounce
Is there any way to prevent the keyboard from bouncing when changing the focus state in onSubmit? Or is it not recommended to change focus in onSubmit? The following view is setup so that pressing return on the keyboard should cause focus to move between the TextFields. struct TextFieldFocusState: View { enum Field { case field1 case field2 } @FocusState var focusedField: Field? var body: some View { Form { TextField("Field 1", text: .constant("")) .focused($focusedField, equals: .field1) .onSubmit { focusedField = .field2 } TextField("Field 2", text: .constant("")) .focused($focusedField, equals: .field2) .onSubmit { focusedField = .field1 } } } } I would expect that when pressing return, the keyboard would say on screen. What actually happens is the keyboard appears to bounce when the return key is pressed (first half of gif). I assume this is because onSubmit starts dismissing the keyboard then setting the focus state causes the keyboard to be presented again. The issue doesn't occur when tapping directly on the text fields to change focus (second half of gif).
2
4
582
1d
NavigationTitle in LiquidGlass style
Hello everyone. I want to do navigationTitle (located on the top side on MacOS system) in LiquidGlass style. now my solution look like: just black rectangle. But i want like this: opacity and LiquidGlass. Like in Photo app in MacOS. Please help me, thank you in advance. My code: struct RootView: View { @Environment(\.horizontalSizeClass) var hSize var body: some View { if hSize == .regular { DesktopLayout() .navigationTitle("title") .toolbarBackground(.ultraThinMaterial, for: .automatic) } else { MobileLayout() } } }
0
0
217
1d
SwiftUI mysterious behavior
Hello dear developers! Recently, I stumbled upon some really strange behavior of SwiftUI and I’m very curious why it works this way struct ContentView: View { @State private var title: String? @State private var isSheetPresented: Bool = false var body: some View { Button("Hello, world!") { title = "Sheet title" isSheetPresented = true } .sheet(isPresented: $isSheetPresented, content: { if let title { Text(title) } else { EmptyView() } }) } } Why in this case when we tap the button and sheet comes in we go to the branch else even though we set title before isSheetPresented but it still somehow nil But what really drive me crazy is that if we change a little bit code to this: I just added another @State property 'number' and use it as the Button's title. In this scenario it works 😃 and Text in the sheet view appearing struct ContentView: View { @State private var title: String? @State private var number = 0 @State private var isSheetPresented = false var body: some View { Button("\(number)") { title = "Sheet title" number += 0 isSheetPresented = true } .sheet(isPresented: $isSheetPresented, content: { if let title { Text(title) } else { EmptyView() } }) } } Is this somehow related to what happens under the hood like View Tree and Render Tree (Attribute Graph)? Maybe because ContentView’s body doesn't capture title it cannot be stored in the Render Tree so it always would have the initial value of nil? if there are any well-informed folks here, please help me figure out this mystery, I’d appreciate it!!! p.s. Don’t get me wrong. Im not interested in how to make it work. I’m interested in why this doesn’t work and what really happens under the hood that led to this result
1
0
79
2d
SwiftUI List: observable reference types not deallocated immediately after refresh
Hello 👋 I ran into a SwiftUI lifecycle gotcha while debugging a List with .refreshable I share the code used to reproduce the issue @Observable final class CounterModel: Identifiable { let id: String var title: String var value: Int init(id: String, title: String, value: Int = 0) { self.id = id self.title = title self.value = value } deinit { print("deinit", title) } } @Observable final class ObservableCountersStore { var counters: [CounterModel] = [ .init(id: "1", title: "A"), .init(id: "2", title: "B"), .init(id: "3", title: "C") ] func refresh() async { try? await Task.sleep(nanoseconds: 300_000_000) counters = [.init(id: "4", title: "D")] } } struct ObservableCountersListView: View { @State private var store = ObservableCountersStore() var body: some View { List { ForEach(store.counters) { counter in ObservableCounterRow(counter: counter) } } .refreshable { await store.refresh() } } } struct ObservableCounterRow: View { let counter: CounterModel var body: some View { Text(counter.title) } } Observation: After calling refresh(), only some of the previous CounterModel only one CounterModel is deallocated immediately. Others are retained This doesn’t look like a leak, but it made me realize that passing observable reference types directly into List rows leads to non-deterministic object lifetimes, especially with .refreshable. Posting this as a gotcha — curious if this matches intended behavior or if others have run into the same thing.
2
0
132
3d
How to do settings icon for menu in SwiftUI?
Hi everyone. Can you help me with my settings icon design. I`m trying to create circular setting button using Menu. My code here: struct MenuView: View { var body: some View { Menu { Text("Hello") Text("How are you") } label: { Image(systemName: "gearshape.fill") .clipShape(Circle()) } .clipShape(Circle()) .padding(.top, 10) .padding(.leading, 20) } } You can see my try, this one looks wrong. It should be like this: Just Circle with setting image inside. Thank you an advance 😭🙏🛐
1
0
450
3d
SwiftUI Menu label: How to center an icon inside a circle?
Hi Everyone. Can you help me with my settings icon design. I'm trying to create a circular settings button using Menu. My code here: struct MenuView: View { var body: some View { Menu { Text("Hello") Text("How are you") } label: { Image(systemName: "gearshape.fill") .clipShape(Circle()) } .clipShape(Circle()) .padding(.top, 10) .padding(.leading, 20) } } You can see my try, this one looks wrong. It should be like this: Just Circle with setting image inside. Thank you an advance 😭🙏🛐
1
0
411
3d
Does Showing User's Current Location on the Map Require 'NSLocationWhenInUseUsageDescription'?
I have a desktop application that shows some real estate properties chosen by the user. The application shows those GPP locations on the map. The SwiftUI code is something like the following. import SwiftUI import MapKit struct ContentView: View { var body: some View ZStack { mapView } } private var mapView: some View { Map(position: $propertyViewModel.mapPosition) { ForEach(propertyViewModel.properties) { property in Annotation("", coordinate: CLLocationCoordinate2D(latitude: property.lat, longitude: property.lon)) { Button { } label: { VStack { Image(systemName: "house.circle.fill") .resizable() .scaledToFit() .frame(width: 48) .foregroundStyle(colorScheme == .light ? .white : .black) ... } } .buttonStyle(.borderless) } } UserAnnotation() } .mapControls { MapUserLocationButton() } .mapControlVisibility(.visible) .onAppear { CLLocationManager().requestWhenInUseAuthorization() } } } The application only wants to use the CLLocationManager class so that it can show those locations on the map relative to your current GPS position. And I'm hit with two review rejections. Guideline 5.1.1 - Legal - Privacy - Data Collection and Storage Issue Description One or more purpose strings in the app do not sufficiently explain the use of protected resources. Purpose strings must clearly and completely describe the app's use of data and, in most cases, provide an example of how the data will be used. Guideline 5.1.5 - Legal - Privacy - Location Services The app uses location data for features that are not relevant to a user's location. Specifically, the app is not functional when Location Services are disabled. So I wonder if the application is even required to have 'NSLocationWhenInUseUsageDescription' and/or 'NSLocationUsageDescription'? just in order to show user's current location so that they can see property locations relative to it? The exact location privacy statement is the following. The application needs your permission in accessing your current location so that it will appear on the map
1
0
77
4d
Delete Confirmation Dialog Inside Toolbar IOS26
inline-code How do you achieve this effect in toolbar? Where is the documentation for this? How to make it appear top toolbar or bottom toolbar? Thank you! Here is what I have now... .toolbar { ToolbarItem(placement: .destructiveAction) { Button { showConfirm = true } label: { Image(systemName: "trash") .foregroundColor(.red) } } } .confirmationDialog( "Are you sure?", isPresented: $showConfirm, titleVisibility: .visible ) { Button("Delete Item", role: .destructive) { print("Deleted") } Button("Archive", role: .none) { print("Archived") } Button("Cancel", role: .cancel) { } } }
1
0
174
4d
How do i use dynamic data for my SwiftUI ScrollView without destroying performance?
Currently i am trying really hard to create experience like the Apple fitness app. So the main view is a single day and the user can swipe between days. The week would be displayed in the toolbar and provide a shortcut to scroll to the right day. I had many attempts at solving this and it can work. You can create such an interface with SwiftUI. However, changing the data on every scroll makes limiting view updates hard and additionally the updates are not related to my code directly. Instruments show me long updates, but they belong to SwiftUI and all the advice i found does not apply or help. struct ContentView: View { @State var journey = JourneyPrototype(selection: 0) @State var position: Int? = 0 var body: some View { ScrollView(.horizontal) { LazyHStack(spacing: 0) { ForEach(journey.collection, id: \.self) { index in Listing(index: index) .id(index) } } .scrollTargetLayout() } .scrollTargetBehavior(.paging) .scrollPosition(id: $position) .onChange(of: position) { oldValue, newValue in journey.selection = newValue ?? 0 journey.update() } .onScrollPhaseChange { oldPhase, newPhase in if newPhase == .idle { journey.commit() } } } } struct Listing: View { var index: Int var body: some View { List { Section { Text("Title") .font(.largeTitle) .padding() } Section { Text("\(index)") .font(.largeTitle) .padding() } Section { Text("1 ") Text("2 ") Text("3 ") Text("4 ") Text("5 ") Text("6 ") } } .containerRelativeFrame(.horizontal) } } @Observable class JourneyPrototype { var selection: Int var collection: [Int] var nextUp: [Int]? init(selection: Int) { self.selection = selection self.collection = [selection] Task { self.collection = [-2,-1,0,1,2] } } func update() { self.nextUp = [ self.selection - 2, self.selection - 1, selection, self.selection + 1, self.selection + 2 ] } func commit() { self.collection = self.nextUp ?? self.collection self.nextUp = nil } } #Preview { ContentView() } There are some major Problem with this abstracted prototype ScrollView has no good trigger for the update, because if i update on change of the position, it will update much more than once. Thats why i had to split calculation and applying the diff The LazyHStack is not optimal, because there are only 5 View in the example, but using HStack breaks the scrollPosition Each scroll updates all List, despite changing only 2 numbers in the array. AI recommended to append and remove, which does nothing about the updates. In my actual Code i do this with Identifiable data and the Problem is the same. So the data itself is not the problem? Please consider, this is just the rough prototype to explain the problem, i am aware that an array of Ints is not ideal here, but the problem is the same in Instruments and much shorter to post. Why am i posting this? Scrolling through dynamic data is required for many apps, but there is no proper solution to this online. Github and Blogs are fine with showing a progress indicator and letting the user wait, some probably perform worse than this prototype. Other solutions require UIKit like using a UIPageViewController. But even using this i run in small hitches related to layout. Important consideration, my data for the scrollview is too big to be calculated upfront. 100 years of days that are calculated for my domain logic take too long, so i have no network request, but the need to only act on a smaller window of data. Instruments shows long update for one scroll action tested on a iPhone SE 2nd generation ListRepresentable has 7 updates and takes 17ms LazySubViewPlacements has 2 updates and takes 8ms Other long updates are too verbose to include I would be very grateful for any help.
0
0
45
4d