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

SwiftUI - Drag gesture blocks scroll gesture only on iPhone 11
I'm pretty new to Swift and SwiftUI. I'm making my first app for sorting a gallery with some extra features. I was using my own iPhone for testing and just started testing my app on other Apple products. Everything works fine on iPad Air M1, iPhone 15 Pro, iPhone 15 Pro Max, iPhone 13, iPhone XS (Simulator), and iPhone 11 Pro (Simulator). However, when I tried to show my app to a family member with an iPhone 11, I came across an issue. Issue Description: My app takes all photos from iPhone's native gallery, then you can sort it by some spesific filters and delete pictures. It just looks like the native gallery. (I can add photos later if needed) You can just scroll the gallery by swiping up and down. You can press the select button and start selecting pictures to delete. I recently added a drag-to-select-multiple-pictures feature. This makes it feel more like the native iOS experience, eliminating the need to tap each picture individually. However, on the iPhone 11, the moment you open the app, you can't scroll. Scrolling is completely locked. You can still select pictures by tapping or dragging, so it's not a touch area issue. The same issue persists on the iPhone 11 simulator. And I think I found the problematic part in my (sadly messy) ContentView.swift file; ScrollView { RefreshControl(coordinateSpace: .named("refresh")) { await viewModel.refreshMediaItems() } LazyVGrid(columns: gridColumns, spacing: UIDevice.current.userInterfaceIdiom == .pad ? 12 : 4) { let items = viewModel.filteredItems(typeFilter: mediaTypeFilter, specialFilter: specialFilter) ForEach(Array(zip(items.indices, items)), id: \.1.id) { index, item in MediaThumbnailView( item: item, isSelected: selectedItems.contains(item.id), viewModel: viewModel, onLongPress: { if !isSelectionMode { toggleSelectionMode() selectedItems.insert(item.id) } }, onTap: { if isSelectionMode { toggleSelection(item: item) } else { viewModel.selectItem(item) } } ) .aspectRatio(1, contentMode: .fit) .background( GeometryReader { geometry in let frame = geometry.frame(in: .named("grid")) Color.clear.preference( key: ItemBoundsPreferenceKey.self, value: [ItemBounds(id: item.id, bounds: frame, index: index)] ) } ) } } .padding(.horizontal, 2) .coordinateSpace(name: "grid") .onPreferenceChange(ItemBoundsPreferenceKey.self) { bounds in itemBounds = Dictionary(uniqueKeysWithValues: bounds.map { ($0.id, $0) }) itemIndices = Dictionary(uniqueKeysWithValues: bounds.map { ($0.id, $0.index) }) } .gesture( DragGesture(minimumDistance: 0) .onChanged { gesture in if isSelectionMode { let location = gesture.location if !isDragging { startDragging(at: location, in: itemBounds) } updateSelection(at: location, in: itemBounds) } } .onEnded { _ in endDragging() } ) } .coordinateSpace(name: "refresh") } you can see the .gesture(.... part. I realised that this DragGesture and ScrollView blocks each other (somehow only on iPhone 11) highPriorityGesture also won't work. When I change it with simultaneousGesture, scroll starts to work again. BUT - since it's simultaneous, when multiple selection mode is activated, when I'm dragging my finger gallery also starts to scroll and it becomes a very unpleasant experience. After this issue I realised on native gallery iOS locks scroll when you are dragging for multiple selection and just when you release your finger you can scroll again even if the multiple selection mode is active. I tried a million things, asked claude, chatgpt etc. etc. Found some similar issues on stackoverflow but they were all related to iOS 18, not spesific to an iPhone. My app works fine on iOS 18 (15 Pro Max) iOS 18 drag gesture blocks scrollview Here are the some of the things I've tried: using highPriorityGesture and simultenousgesture together, tried to lock the scroll briefly while dragging, implement much complicated versions of these things with the help of claude, try to check if isSelectionMode is true or not All of them broke other things/won't work. Probably there's something pretty simple that I'm just missing; but iPhone 11 being the single problematic device confuses me. I don't want to mess too much with my already fragile logic.
1
0
297
Jan ’25
How to zoom with camera preview
Hey everyone, I'm using this view code to create a camera preview for my app. I wanted to create a zoom experience when you pinch. I know how ton do this for images, but not for a view like this. Does anyone know anything that could help? Thank you.
0
0
342
Jan ’25
Is it possible to make GeometryReader less vertically greedy?
I must be missing something here. I want to put a landscape image in a geometry reader that contains a ZStack that contains an image and an overlay centred on top of the Image. I would like the ZStack and GeoReader's sizes to be the size of Image. (ie I want geometry.size to be the size of the image, which can be used to control the offset of the overlay's position.) Unfortunately the ZStack also includes the space above the image (ie the top safeArea) and the GeometryReader also includes all the space below the Image. (so geometry.size.height is greater than the height of Image) I've gone down rabbit holes of adding other items above/below, but I don't seem to be able to prevent the GeometryReader from being vertically greedy. eg the Text(" ") above the ZStack in the VStack solves the ZStack claiming the top safe area. But adding Text(" ") below the ZStack does not prevent the GeometryReader from claiming more vertical space below the image. Any/all guidance greatly appreciated. struct ContentView: View { var body: some View { VStack { // Text(" ") GeometryReader { geometry in ZStack { Image( uiImage: .init(imageLiteralResourceName: "LandscapeSample") ) .resizable() .aspectRatio(contentMode: .fit) Text("Hello, world!") .background(.white) } .background(.red) } .background(.blue) // Text(" ") } } }
2
0
428
Jan ’25
Start tvOS SideBar Menu Collapsed
I'm trying to make the side bar menu on my tvOS app have the same behavior of Apple's tvOS App. I would like to have the side menu collapsed at the cold start of the app. I'm trying to achieve this by using the defaultFocus view modifier, which should make the button inside the TabView focused at the start of the app. But no matter what I do, the side bar always steels the focus from the inside button. struct ContentView: View { enum Tabs { case viewA case viewB } enum ScreenElements { case button case tab } @FocusState private var focusedElement: ScreenElements? @State private var selectedTab: Tabs? = nil var body: some View { Group { TabView(selection: $selectedTab) { Tab("View A", image: "square", value: .viewA) { Button("View A Button", action: {}) .frame(maxWidth: .infinity, alignment: .center) .focused($focusedElement, equals: .button) } } .tabViewStyle(.sidebarAdaptable) .focused($focusedElement, equals: .tab) } .defaultFocus($focusedElement, .button, priority: .userInitiated) } } Is there a way to start the side bar menu collapsed at the start up of the app?
0
0
370
Jan ’25
SwiftUI infinite rendering loop when using a custom Binding to a dictionary-based store
I’m building a SwiftUI app where the struct AppGroup is identified by a UUID and stored in a dictionary. My Task model has appGroupId: UUID?. In TaskDetailView, I create a custom Binding<AppGroup> from the store, then navigate to AppGroupDetailView. However, when I tap the NavigationLink, the console spams logs, CPU hits 100%, and it never stabilizes. Relevant Code AppGroupStore (simplified) class AppGroupStore: ObservableObject { @Published var appGroupsDict: [UUID: AppGroup] = [:] func updateAppGroup(_ id: UUID, appGroup: AppGroup) { appGroupsDict[id] = appGroup } // Returns a binding so views can directly read/write the AppGroup by id func getBinding(withId id: UUID?) -> Binding<AppGroup> { Binding( get: { if let id = id { return self.appGroupsDict[id] ?? .empty } return .empty }, set: { newValue in print("New value set for \(newValue.name)") self.updateAppGroup(newValue.id, appGroup: newValue) } ) } // ... } AppGroup is a simple struct: struct AppGroup: Identifiable, Codable { let id: UUID var name: String var apps: [String] static let empty = AppGroup(id: UUID(), name: "Empty", apps: []) } TaskDetailView (main part) struct TaskDetailView: View { @Binding var task: ToDoTask // has task.appGroupId: UUID? @EnvironmentObject var appGroupStore: AppGroupStore var body: some View { let appGroup = appGroupStore.getBinding(withId: task.appGroupId) print("Task load") // prints infinitely, CPU 100% return List { // ... NavigationLink(destination: AppGroupDetailView(appGroup: appGroup)) { Text(appGroup.wrappedValue.name) } } .navigationTitle(task.name) } } AppGroupDetailView (simplified) struct AppGroupDetailView: View { @Binding var appGroup: AppGroup // ... var body: some View { List { ForEach(appGroup.apps, id: \.self) { app in Text(app) } } .navigationTitle(appGroup.name) } } Symptoms: Tapping the NavigationLink leads to infinite “Task load” logs and 100% CPU usage. The set closure (“New value set for...”) is never called, so it’s not repeatedly writing. If I replace the Binding<AppGroup> with a read-only approach (just accessing the dictionary), it does not get stuck. Question: What might cause SwiftUI to keep re-rendering the body indefinitely, even if my custom get closure doesn’t explicitly mutate the state? Are there known pitfalls when using a dictionary-based store and returning a Binding like this? Any help is much appreciated! Thanks in advance for your insights!
0
0
220
Jan ’25
ShareLink does not prompt inside of fullScreenCover
When I try to launch a ShareLink from within a fullScreenCover, I get the following error: Attempt to present <UIActivityViewController: 0x105e6a400> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x1053a37c0> (from <_TtGC7SwiftUI19UIHostingControllerVVS_7TabItem8RootView_: 0x105eb8a00>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x114890000> Seems like a bug, has anyone else encountered this or found a way around it?
1
0
191
Jan ’25
Popover in full-screen apps doesn't keep menu bar open
I have an app that acts as an agent (no dock/app, just menu bar icon). When the icon is clicked, I show a popover with a small user interface. This works great, however, there is an issue. When a certain app is in full-screen and then my menu bar icon is clicked, the user interface shows just fine, until the mouse is moved outside the menu bar - then the user interface stays but the menu bar dismisses and closes. Is there a way to keep the menu bar open, like when clicking on Control Center, in full-screen apps? This is how I open my popover: if let button = statusItem.button { if popover.isShown { self.popover.performClose(sender) } else { popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY) popover.contentViewController?.view.window?.makeKey() } } }
2
0
213
Jan ’25
TabView and Swift Charts giving inconsistent behaviour when swiping between pages
Hi there, I have a TabView in page style. Inside that TabView I have a number of views, each view is populated with a model object from an array. The array is iterated to provide the chart data. Here is the code: TabView(selection: $displayedChartIndex) { ForEach((0..<data.count), id: \.self) { index in ZStack { AccuracyLineView(graphData: tabSelectorModel.lineChartModels[index]) .padding(5) } .tag((index)) } } .tabViewStyle(.page) .indexViewStyle(.page(backgroundDisplayMode: .always)) I am seeing odd behaviour, as I swipe left and right, occasionally the chart area shows the chart from another page in the TabView. I know the correct view is being shown as there are text elements. See the screenshot below. The screen on the right is running iOS 17.2 and this works correctly. The screen on the left is running iOS 17.4 and the date at the top is correct which tells me that the data object is correct. However the graph is showing a chart from a different page. When I click on the chart on the left (I have interaction enabled) then it immediately draws the correct chart. If I disable the interaction then I still get the behaviour albeit the chart never corrects itself because there is no interaction! I can reproduce this in the 17.4 simulator and it is happening in my live app on iOS17.4. This has only started happening since iOS 17.4 dropped and works perfectly in iOS 17.2 simulator and I didn't notice it in the live app when I was running 17.3. Is this a bug and/or is there a workaround? For info this is the chart view code, it is not doing anything clever: struct AccuracyLineView: View { @State private var selectedIndex: Int? let graphData: LineChartModel func calcHourMarkers (maxTime: Int) -> [Int] { let secondsInDay = 86400 // 60 * 60 * 24 var marks: [Int] = [] var counter = 0 while counter <= maxTime { if (counter > 0) { marks.append(counter) } counter += secondsInDay } return marks } var selectedGraphMark: GraphMark? { var returnMark: GraphMark? = nil var prevPoint = graphData.points.first for point in graphData.points { if let prevPoint { if let selectedIndex, let lastPoint = graphData.points.last, ((point.interval + prevPoint.interval) / 2 > selectedIndex || point == lastPoint) { if point == graphData.points.last { if selectedIndex > (point.interval + prevPoint.interval) / 2 { returnMark = point } else { returnMark = prevPoint } } else { returnMark = prevPoint break } } } prevPoint = point } return returnMark } var body: some View { let lineColour:Color = Color(AppTheme.globalAccentColour) VStack { HStack { Image(systemName: "clock") Text(graphData.getStartDate() + " - " + graphData.getEndDate()) // 19-29 Sept .font(.caption) .fontWeight(.light) Spacer() } Spacer() Chart { // Lines ForEach(graphData.points) { item in LineMark( x: .value("Interval", item.interval), y: .value("Offset", item.timeOffset), series: .value("A", "A") ) .interpolationMethod(.catmullRom) .foregroundStyle(lineColour) .symbol { Circle() .stroke(Color(Color(UIColor.secondarySystemGroupedBackground)), lineWidth: 4) .fill(AppTheme.globalAccentColour) .frame(width: 10) } } ForEach(graphData.trend) { item in LineMark ( x: .value("Interval", item.interval), y: .value("Offset", item.timeOffset) ) .foregroundStyle(Color(UIColor.systemGray2)) } if let selectedGraphMark { RuleMark(x: .value("Offset", selectedGraphMark.interval)) .foregroundStyle(Color(UIColor.systemGray4)) } } .chartXSelection(value: $selectedIndex) .chartXScale(domain: [0, graphData.getMaxTime()]) } } }
10
0
1.7k
Jan ’25
Excessive ressource usage with NavigationLinks in LazyVStack
When a large number of NavigationLinks is within a LazyVStack (or LazyVGrid), ressource usage gets higher (and stays high) the further a user scrolls down. A simple example to reproduce this: NavigationStack { ScrollView { LazyVStack { ForEach(0..<5000) { number in NavigationLink(value: number) { Text("Number \(number)") } } } } .navigationDestination(for: Int.self) { number in Text("Details for number \(number)") } } List does not exhibit this behavior but is not suitable for my use case.
1
0
238
Jan ’25
Implement two lists side by side with SwiftUI on iPad
I'm currently building an App using a TabView as the main navigation method. In my app I would like to build a page similar to the Top Charts in the native App Store App with two lists side by side: So far I came up with this code (simplified demo): import SwiftUI struct Demo: View { var body: some View { TabView { Tab("Main Tab", systemImage: "tray.and.arrow.down.fill") { NavigationStack { HStack { List { Text("Left List") } List { Text("Right List") } } .navigationTitle("Demo") .navigationBarTitleDisplayMode(.inline) } } } } } #Preview { Demo() } However, I’m encountering a couple of issues: • Scrolling to the top of the left list doesn’t trigger the toolbar background effect, and the content overlaps with the tabs in a strange way. Scrolling to the top of the right list works as expected. • The navigation title is always hidden. I haven’t been able to find a solution to these problems. What would be the correct approach? Thank you!
1
0
546
Jan ’25
Production app crashing with PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:)
Hello, my production app is experiencing some crashes according to app store analytics. I cannot seem to reproduce it. According to Xcode Orginzer the app is crashing 10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699) Distributor ID: com.apple.AppStore Hardware Model: iPhone13,4 Version: 2.0.3 (86) AppStoreTools: 15E204 AppVariant: 1:iPhone13,4:16 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] OS Version: iPhone OS 17.4.1 (21E236) Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 name: Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001d1bd6974 __pthread_kill + 8 (:-1) 1 libsystem_pthread.dylib 0x00000001e56590ec pthread_kill + 268 (pthread.c:1717) 2 libsystem_c.dylib 0x0000000191627c14 __abort + 136 (abort.c:159) 3 libsystem_c.dylib 0x0000000191627b8c abort + 192 (abort.c:126) 4 libswiftCore.dylib 0x000000018832a690 swift::fatalErrorv(unsigned int, char const*, char*) + 136 (Errors.cpp:387) 5 libswiftCore.dylib 0x000000018832a6b0 swift::fatalError(unsigned int, char const*, ...) + 32 (Errors.cpp:395) 6 libswiftCore.dylib 0x0000000188324a08 getNonNullSrcObject(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InProcess&gt; const*) + 256 (DynamicCast.cpp:144) 7 libswiftCore.dylib 0x0000000188326510 tryCastToObjectiveCClass(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InPro... + 88 (DynamicCast.cpp:510) 8 libswiftCore.dylib 0x0000000188324068 tryCast(swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::OpaqueValue*, swift::TargetMetadata&lt;swift::InProcess&gt; const*, swift::TargetMetadata&lt;swift::InProcess&gt; const*&amp;, sw... + 992 (DynamicCast.cpp:2281) 9 libswiftCore.dylib 0x0000000188323b14 swift_dynamicCast + 208 (CompatibilityOverrideRuntime.def:109) 10 SwiftUI 0x000000018ec372a0 PlatformViewHost.updateNestedHosts(_:colorSchemeChanged:) + 332 (PlatformViewHost.swift:699) 11 SwiftUI 0x000000018ec36bf4 PlatformViewHost.updateEnvironment(_:viewPhase:) + 412 (PlatformViewHost.swift:690) 12 SwiftUI 0x000000018ec37bf8 PlatformViewHost.init(_:host:environment:viewPhase:importer:) + 808 (PlatformViewHost.swift:132) 13 SwiftUI 0x000000018ec36cf8 PlatformViewHost.__allocating_init(_:host:environment:viewPhase:importer:) + 92 (PlatformViewHost.swift:0) 14 SwiftUI 0x000000018ec0132c closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 444 (PlatformViewRepresentable.swift:559) 15 SwiftUI 0x000000018ec06c58 partial apply for closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (&lt;compiler-generated&gt;:0) 16 SwiftUI 0x000000018ea26910 RepresentableContextValues.asCurrent&lt;A&gt;(do:) + 156 (RepresentableContextValues.swift:43) 17 SwiftUI 0x000000018ec01124 closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 176 (PlatformViewRepresentable.swift:558) 18 SwiftUI 0x000000018ec0104c closure #4 in closure #1 in PlatformViewChild.updateValue() + 128 (PlatformViewRepresentable.swift:557) 19 SwiftUI 0x000000018ec06b2c partial apply for closure #4 in closure #1 in PlatformViewChild.updateValue() + 24 (&lt;compiler-generated&gt;:0) 20 SwiftUI 0x000000018de7b7d0 closure #1 in _withObservation&lt;A&gt;(do:) + 44 (ObservationUtils.swift:26) 21 SwiftUI 0x000000018ec06b50 partial apply for closure #1 in _withObservation&lt;A&gt;(do:) + 24 (&lt;compiler-generated&gt;:0) 22 libswiftCore.dylib 0x0000000187fd0068 withUnsafeMutablePointer&lt;A, B&gt;(to:_:) + 28 (LifetimeManager.swift:82) 23 SwiftUI 0x000000018ebffbdc closure #1 in PlatformViewChild.updateValue() + 3040 (PlatformViewRepresentable.swift:556) 24 SwiftUI 0x000000018d5ecbf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init&lt;A&gt;(_:) + 32 (&lt;compiler-generated&gt;:0) 25 AttributeGraph 0x00000001b2150240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 26 AttributeGraph 0x00000001b2146f38 AG::Graph::update_attribute(AG::data::ptr&lt;AG::Node&gt;, unsigned int) + 424 (ag-graph-update.cc:719) 27 AttributeGraph 0x00000001b2146810 AG::Graph::input_value_ref_slow(AG::data::ptr&lt;AG::Node&gt;, AG::AttributeID, unsigned int, unsigned int, AGSwiftMetadata const*, unsigned char&amp;, long) + 720 (ag-graph.cc:1429)
3
5
1.1k
Jan ’25
Multi Section Sidebar using List with selections for macOS
I'm trying to implement a 3 column NavigationSplitView in SwiftUI on macOS - very similar to Apple's own NavigationCookbook sample app - with the slight addition of multiple sections in the sidebar similar to how the Apple Music App has multiple sections in the sidebar. Note: This was easily possible using the deprecated NavigationLink(tag, selection, destination) API The most obvious approach is to simply do something like: NavigationSplitView(sidebar: { List { Section("Section1") { List(section1, selection: $selectedItem1) { item in NavigationLink(item.label, value: item) } } Section("Section2") { List(section2, selection: $selectedItem2) { item in NavigationLink(item.label, value: item) } } } }, content: { Text("Content View") }, detail: { Text("Detail View") }) But unfortunately, this doesn't work - it doesn't seem to properly iterate over all of the items in each List(data, selection: $selected) or the view is strangely cropped - it only shows 1 item. However if the 1 item is selected, then the appropriate bindable selection value is updated. See image below: If you instead use ForEach for enumerating the data, that does seem to work, however when you use ForEach, you loose the ability to track the selection offered by the List API, as there is no longer a bindable selection propery in the NavigationLink API. NavigationSplitView(sidebar: { List { Section("Section1") { ForEach(section1) { item in NavigationLink(item.label, value: item) } } Section("Section2") { ForEach(section2) { item in NavigationLink(item.label, value: item) } } } }, content: { Text("Content View") }, detail: { Text("Detail View") }) We no longer know when a sidebar selection has occurred. See image below: Obviously Apple is not going to comment on the expected lifespan of the now deprecated API - but I am having a hard time switching to the new NavigationLink with a broken sidebar implementation.
3
0
554
Jan ’25
Does EV Charging entitlement support CPSearchTemplate?
I am developing a CarPlay app, that has been approved for EV Charging entitlement. Could you please confirm if the given entitlement supports CPSearchTemplate template as there is some confusion here. I tried using the template by referring to the below link, https://developer.apple.com/documentation/carplay/cpsearchtemplate Here is the snippet, class SearchCPView: UIResponder, CPSearchTemplateDelegate { var searchTemplate: CPSearchTemplate = CPSearchTemplate() override init() { super.init() searchTemplate.delegate = self } func getSearchTemplate(interfaceController: CPInterfaceController?) -> CPGridTemplate { let searchGridButton = CPGridButton(titleVariants: [CarplayButtonTitles.search], image: UIImage(named: ImagesConstants.CarPlay.searchGrid) ?? UIImage(), handler: {[self] _ in guard let controller = interfaceController else { return } controller.pushTemplate(self.searchTemplate, animated: true) { status, error in print(status) } }) let gridTemplate = CPGridTemplate(title: "", gridButtons: [searchGridButton]) return gridTemplate } func searchTemplate(_ searchTemplate: CPSearchTemplate, selectedResult item: CPListItem) async { print(item) } func searchTemplate(_ searchTemplate: CPSearchTemplate, updatedSearchText searchText: String) async -> [CPListItem] { print(searchText) return [CPListItem(text: "", detailText: "")] } } On push, I am getting an exception, *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported object <CPSearchTemplate: 0x30056df00> <identifier: 28, userInfo: (null), tabTitle: (null), tabImage: (null), showsTabBadge: 0> passed to pushTemplate:animated:completion:. Allowed classes: {( CPTabBarTemplate, CPActionSheetTemplate, CPAlertTemplate, CPGridTemplate, CPPointOfInterestTemplate, CPInformationTemplate, CPContactTemplate, CPListTemplate )}'
1
0
326
Jan ’25
How to test iPhone app and CarPlay together?
I have developed a mobile app using SwiftUI. Now I am in the process of building a CarPlay application. I know how to test the CarPlay app using a simulator but here is my confusion, Testing the iPhone app and CarPlay together (few scenarios like user login / logout, location enabled /disabled in the mobile app) Kindly help me validate the above scenarios as I am getting black screen on iPhone whenever the CarPlay is launched. Below is the code snippet, func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if connectingSceneSession.role == .carTemplateApplication { let sceneConfiguration = UISceneConfiguration(name: "CarPlay Scene", sessionRole: connectingSceneSession.role) sceneConfiguration.delegateClass = CarPlaySceneDelegate.self return sceneConfiguration } // Configuration for other types of scenes return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } struct MyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() .preferredColorScheme(.light) } } } Info.plist <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>CPTemplateApplicationSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>CarPlay Scene</string> <key>UISceneDelegateClassName</key> <string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string> </dict> </array> </dict> </dict>
1
0
413
Jan ’25
Using txt files with searching strings for an iOS app
When dealing with SwiftUI and searchable modifier, I know you can use URL or hard code data to search when building projects in Xcode. I am looking to see if you can use a txt file as a way or storing string data of lists to search from when your device is offline when using the search modifier. Then when connected to internet you can update the search with url connection that then updates the txt file so you can do new searches the next time you are offline again. Is this something that is possible?
0
0
240
Jan ’25
Can't Widgetkit use lottie to implement the isOn state of toggle?
I introduced lottie to toggle in my widget to show a transition animation, but found that the.json file wouldn't load. The loading_hc.json file is validated and exists in the widget target. Ask for help, thank you! struct LottieView: UIViewRepresentable { let animationName: String func makeUIView(context: Context) -> LOTAnimationView { let lotAnimationView = LOTAnimationView(name: animationName, bundle: .main) lotAnimationView.contentMode = .scaleAspectFit lotAnimationView.play() return lotAnimationView } func updateUIView(_ uiView: LOTAnimationView, context: Context) { } func makeCoordinator() -> Coordinator { Coordinator() } } struct ControlToggleDisarmingStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { if configuration.isOn { LottieView(animationName: "loading_hc.json").foregroundColor(.clear).frame(width: 24,height: 24) } else { Image("icon_disarm", bundle: Bundle.main).foregroundColor(.clear) } } }
2
0
441
Jan ’25
How to test iPhone app and CarPlay together?
I have developed a mobile app using SwiftUI. Now I am in the process of building a CarPlay application. I know how to test the CarPlay app using a simulator but here is my confusion, How to test the iPhone app and CarPlay together? I want to test few scenarios like, user login / logout from mobile app. Location enabled /disabled in the mobile app. I know that swiftUI handles the scenes by itself. Kindly help me validate the above scenarios as I am getting black screen on iPhone whenever the CarPlay is launched. Below is the code snippet, func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if connectingSceneSession.role == .carTemplateApplication { let sceneConfiguration = UISceneConfiguration(name: "CarPlay Scene", sessionRole: connectingSceneSession.role) sceneConfiguration.delegateClass = CarPlaySceneDelegate.self return sceneConfiguration } // Configuration for other types of scenes return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } struct MyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() .preferredColorScheme(.light) } } } Info.plist <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>CPTemplateApplicationSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>CarPlay Scene</string> <key>UISceneDelegateClassName</key> <string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string> </dict> </array> </dict> </dict>
2
0
595
Jan ’25
iPadOS 18 TabView with Large Navigation Title
I’m following the example code from Apple to implement the new iPadOS 18 TabView() with the new Tab(). While the tabbing itself is working fine, I can’t get it to show up a (large) navigation title in the sidebar (like the Home or Files app). I’ve tried placing .navigationTitle("App Name") at the TabView, but that doesn’t work. Is it possible to do this in any way or is this not recommended to show? TabView { Tab("Overview", systemImage: "film") { Text("Put a OverviewView here") } TabSection("Watch") { Tab("Movies", systemImage: "film") { Text("Put a MoviesView here") } Tab("TV Shows", systemImage: "tv") { Text("Put a TVShowsView here") } } TabSection("Listen") { Tab("Music", systemImage: "music.note.list") { Text("Put a MusicView here") } Tab("Podcasts", systemImage: "mic") { Text("Put a PodcastsView here") } } } .tabViewStyle(.sidebarAdaptable) .navigationTitle("App Name") .navigationBarTitleDisplayMode(.large) I know that there is also the .tabViewSidebarHeader() modifier, but that adds any view above the scroll view content. Neither does that easily allow to make it look like the regular navigation title, nor does it actually display in the navigation bar at the top, when scrolling down.
2
0
943
Jan ’25