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

SwiftUI Documentation

Posts under SwiftUI tag

2,346 Posts
Sort by:
Post not yet marked as solved
1 Replies
248 Views
In SwiftUI, it looks like when a window is not in view its scene phase is set to ScenePhase.background after a minute or so. Now when every window of an app has been closed, the last window to be closed has its phase set to SchenePhase.background. This makes it quite difficult to differentiate reopening and app from a window that was out of view being glanced at again. I have tried implementing a solution where I count opened/closed window with an onChange that watches scenePhase, but it unfortunately looks like not every window closing gets detected (specifically if there are two windows, with one window is in the background, and the one active window is closed, its scene phase onChange is never triggered). Is there a better way to handle the case of differentiating between reopening an app with looking back at a suspended window that was never actually closed?
Posted
by ncitron.
Last updated
.
Post not yet marked as solved
0 Replies
43 Views
I have added the Journaling Suggestions capability and now I am trying to import journaling suggestions in my app so I can use it, but I am getting the ' No such Module' error, I have quit Xcode and opened it again, I am getting the same issue . I am running Xcode version 15.3
Posted Last updated
.
Post not yet marked as solved
1 Replies
75 Views
Dear Sirs, I'm writing an audio application that should show up to 128 horizontal peakmeters (width for each is about 150, height is 8) stacked inside a ScrollViewReader. For the actual value of the peakmeter I have a binding to a CGFloat value. The peakmeter works as expected and is refreshing correct. For testing I added a timer to my swift application that is firing every 0.05 secs, meaning I want to show 20 values per second. Inside the timer func I'm just creating random CGFloat values in range of 0...1 for the bound values. The peakmeters refresh and flicker as expected but I can see a CPU load of 40-50% in the activity monitor on my MacBook Air with Apple M2 even when compiled in release mode. I think this is quite high and I'd like to reduce this CPU load. Should this be possible? I.e. I thought about blocking the refresh until I've set all values? How could this be done and would it help? What else could I do? Thanks and best regards, JFreyberger
Posted Last updated
.
Post not yet marked as solved
3 Replies
127 Views
Hello, I am new to IOS Development and I am trying to create new project but swift ui view is not showing.
Posted Last updated
.
Post not yet marked as solved
1 Replies
81 Views
Has anyone successfully persisted Color, particularly in SwiftData? So far my attempts have failed: Making Color conform to Codable results in a run time error (from memory something about ColorBox). Color.Resolved already conforms Codable but this results in "SwiftData/ModelCoders.swift:124: Fatal error: Composite Coder only supports Keyed Container" None of the other color types conform to Codable (CGColor, NSColor and UIColor) so does the swift language really not have a persistable color type?
Posted
by Uasmel.
Last updated
.
Post not yet marked as solved
0 Replies
56 Views
I have pushed an UIHostingController which contains SwiftUI and set the navigationBar hidden: class CoverVC : UIHostingController<AnyView>{ public init(shouldShowNavigationBar: Bool, rootView: ICloudSyncView) { super.init(rootView: AnyView(rootView.navigationBarHidden(!shouldShowNavigationBar))) self.navigationController?.interactivePopGestureRecognizer?.delegate = self } @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CoverVC: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } But the InteractivePopGestureRecognizer is disabled. How can I to solve this?
Posted
by WWWang.
Last updated
.
Post not yet marked as solved
0 Replies
53 Views
This is a bug I have been trying to identify and fix for more than 3 weeks. This bug mostly happens in production. The stack trace doesn't help that much, because it looks like the app is crashing due to some SwiftUI internal methods. I tried everything in my power to debug and find this bug, still nothing. Due to the lack of 100% reproducibility, it made me think that this bug is either memory-pressure related or Swift concurrency related. When does it happen: This bug happens when presenting a SwiftUI modal (UIViewControllerRepresentable)[A] which in terms presents a UIHostingController modal[B] which then presents a modally a SwiftUI sheet [C] The bug happens somewhere around staying in [C] or after dismissing it. Context: The app lifecycle is SwiftUI. The main SwiftUI screen in the app body is a UIViewControllerRepresentable containing a UISplitViewController. Here is a screenshot from the crash log in Xcode. Anyone facing a similar issue?
Posted Last updated
.
Post not yet marked as solved
0 Replies
123 Views
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)
Posted
by RFusion.
Last updated
.
Post not yet marked as solved
2 Replies
399 Views
I am generating a USD file with RealityKit and ARKit. I want to, within the same app, open the USD file and display it as if it was a USDZ file. For the user to see, without having to send it to another device. Is this possible? Thanks
Posted Last updated
.
Post not yet marked as solved
0 Replies
79 Views
When the content exceeds 40 lines of text, crazy behaviour starts to happen. The content jumps up and down while typing. Is there any other way to implement simple editor that can handle around 200 lines without this crazy behaviour?
Posted
by m4rqs.
Last updated
.
Post not yet marked as solved
0 Replies
115 Views
I have a container view implementation that reads preference values from child views: public struct Reader<Content>: View where Content: View { public var content: () -> Content public init(@ViewBuilder content: @escaping () -> Content) { self.content = content } public var body: some View { content() .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } } This works fine until the content passed in to the container view is a Group. At that point the onPreferenceChanged modifier is applied to every child of the group, which leads to bugs in my situation. One thing I can do is simply put the content in a VStack: public var body: some View { VStack(content: content) .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } And that works fine to "Ungroup" before applying the onPreferenceChanged modifier. However, is this best practice? Is there a better way to apply a modifier to content as a whole instead of to each member of a potential group? Is it concerning that I might have an extra VStack in the view hierarchy with this fix?
Posted
by rolson.
Last updated
.
Post marked as solved
1 Replies
87 Views
I'm running into this error, when the underlying SwiftData object changes (gets an object added to it): *" A NavigationLink is presenting a value of type “Project” but there is no matching navigationDestination declaration visible from the location of the link. The link cannot be activated. Note: Links search for destinations in any surrounding NavigationStack, then within the same column of a NavigationSplitView. "* For instance, when I first fire up the simulator, clicking on any existing project correctly takes me to its details page. However, as soon as I add a new project or delete a project, none of the navigation links work any more. If I reload the simulator, they all work again! Makes me suspect it's an error with not recomputing the links when the underlying data change, but I can't figure out what I need to change, as everything looks correct. Any help would be appreciated! ContentView: struct ContentView: View { @Environment(\.modelContext) var modelContext @Query(sort: \Project.endDate) var projects: [Project] var body: some View { NavigationStack { Group { if projects.isEmpty { ContentUnavailableView("Enter your first project.", systemImage: "clipboard") } else { List { ForEach(projects, id: \.id) { project in NavigationLink(value: project) { HStack { DaysTile( days: project.numWorkDaysNowUntilEnd, description: "Work Days Remaining" ) .padding(.trailing, 5) VStack(alignment: .leading) { Text(project.name) .font(.title) Text("Start: \(project.startDate.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(.secondary) Text("End: \(project.endDate.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(.secondary) } } } } .onDelete(perform: deleteProjects) } .navigationDestination(for: Project.self) { project in ProjectDetailView(project: project) } } } .navigationTitle("Project Tracker") .toolbar { NavigationLink { AddProjectView() } label: { Label("Add New Project", systemImage: "plus") } } } } func deleteProjects(at offsets: IndexSet) { for offset in offsets { let project = projects[offset] modelContext.delete(project) } } } #Preview { ContentView() .modelContainer(for: Project.self, inMemory: true) }
Posted Last updated
.
Post not yet marked as solved
1 Replies
82 Views
Hello, I am doing to load model from bundle and it is loaded successfully. Now I am scaling model using GestureExtension from apple demo code. (https://developer.apple.com/documentation/realitykit/transforming-realitykit-entities-with-gestures?changes=_8) @State private var selectedEntityName : String = "" @State private var modelEntity: ModelEntity? var body: some View { contentView .task { do { modelEntity = try await ModelEntity.loadArcadeMachine() } catch { fatalError(error.localizedDescription) } } } @ViewBuilder private var contentView: some View { if let modelEntity { RealityView { content, attachments in modelEntity.position = SIMD3<Float>(x: 0, y: -0.3, z: -5) print(modelEntity.transform.scale) modelEntity.transform.scale = [0.006, 0.006, 0.006] content.add(modelEntity) if let percentTextAttachment = attachments.entity(for: "percentage") { percentTextAttachment.position = [0, 50, 0] modelEntity.addChild(percentTextAttachment) } } update: { content, attachments in // I want here to get updated scaling value and it is showing in RealityView attachmnt text. } attachments: { Attachment(id: "percentage") { Text("\(modelEntity.name) \(modelEntity.scale * 100) %") .font(.system(size: 5000)) .background(.red) } } // This method am using for gesture support .installGestures() } else { ProgressView() } } } Below code from GestureExtension let state = EntityGestureState.shared guard canScale, !state.isDragging else { return } let entity = value.entity if !state.isScaling { state.isScaling = true state.startScale = entity.scale } let magnification = Float(value.magnification) entity.scale = state.startScale * magnification state.magnifyValue = magnification magnifyScale = Double(magnification) print("Entity Name ::::::: \(entity.name)") print("Scale ::::::: \(entity.scale)") print("Magnification ::::::: \(magnification)") print("StartScale ::::::: \(state.startScale)") > This "magnification" value I need to use in RealityView class. How can i Do it? Could you please guide it. }
Posted Last updated
.
Post not yet marked as solved
5 Replies
4.7k Views
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
Posted
by ngb.
Last updated
.
Post not yet marked as solved
1 Replies
254 Views
@Query(filter: #Predicate<Note>{ note in note.isDeleted == false && (note.title != "" || note.content != "") } ,sort: [SortDescriptor(\Note.isPinned, order: .reverse),SortDescriptor(\Note.createdAt, order: .reverse)] , animation: .smooth(duration: 0.3) ) private var notes: [Note] if I delete filter part navigationLink works properly
Posted
by AzizK.
Last updated
.
Post not yet marked as solved
0 Replies
96 Views
When I build app on Xcode 15.3 with SWIFT_STRICT_CONCURRENCY=complete, there are some warning. Almost warning can be fixed, but not the TipKit code. Here is the example. Are there any good way to solve it?
Posted
by hcrane.
Last updated
.
Post marked as solved
4 Replies
201 Views
On my shop and content views of my app, I have a shopping cart SF symbol that I've modified with a conditional to show the number of items in the cart if the number of items is above zero. However, whenever I change tabs and back again, that icon disappears even though there should be an item in the cart. I have a video of the error, but I have no idea how to post it. Here is some of the code, let me know if you need to see more of it: CartManager.swift import Foundation import SwiftUI @Observable class CartManager { /*private(set)*/ var products: [Product] = [] private(set) var total: Int = 0 private(set) var numberofproducts: Int = 0 func count() -> Int { numberofproducts = products.count return numberofproducts } func addToCart(product: Product) { products.append(product) total += product.price numberofproducts = products.count } func removeFromCart(product: Product) { products = products.filter { $0.id != product.id } total -= product.price numberofproducts = products.count } } ShopPage.swift import SwiftUI struct ShopPage: View { @Environment(CartManager.self) private var cartManager var columns = [GridItem(.adaptive(minimum: 135), spacing: 0)] @State private var searchText = "" let items = ["LazyHeadphoneBean", "ProperBean", "BabyBean", "RoyalBean", "SpringBean", "beanbunny", "CapBean"] var filteredItems: [Bean] { guard searchText.isEmpty else { return beans } return beans.filter { $0.imageName.localizedCaseInsensitiveContains(searchText) } } var body: some View { NavigationStack { ZStack(alignment: .top) { Color.white .ignoresSafeArea(edges: .all) VStack { AppBar() .environment(cartManager) ScrollView() { LazyVGrid(columns: columns, spacing: 20) { ForEach(productList, id: \.id) { product in NavigationLink { beanDetail(product: product) .environment(cartManager) } label: { ProductCardView(product: product) .environment(cartManager) } } } } } .navigationBarDrawer(displayMode: .always)) } } .environment(cartManager) } var searchResults: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.contains(searchText)} } } } #Preview { ShopPage() .environment(CartManager()) } struct AppBar: View { @Environment(CartManager.self) private var cartManager var body: some View { NavigationStack { VStack (alignment: .leading){ HStack { Spacer() NavigationLink(destination: CartView() .environment(cartManager) ) { CartButton(numberOfProducts: cartManager.products.count) } } Text("Shop for Beans") .font(.largeTitle .bold()) } } .padding() .environment(CartManager()) } } CartButton.swift import SwiftUI struct CartButton: View { var numberOfProducts: Int var body: some View { ZStack(alignment: .topTrailing) { Image(systemName: "cart.fill") .foregroundStyle(.black) .padding(5) if numberOfProducts > 0 { Text("\(numberOfProducts)") .font(.caption2).bold() .foregroundStyle(.white) .frame(width: 15, height: 15) .background(Color(hue: 1.0, saturation: 0.89, brightness: 0.835)) .clipShape(RoundedRectangle(cornerRadius: 50)) } } } } #Preview { CartButton(/*numberOfProducts: 1*/numberOfProducts: 1) }
Posted
by KittyCat.
Last updated
.
Post not yet marked as solved
4 Replies
86 Views
I encountered a problem while using ScrollView in SwiftUI. When I perform a refresh, the app crashes. I access the array using an index in a ForEach loop. This is done to create new data from the array in a commonly used view. The function to create data is adopted from a protocol in the view model. I access it by index because the type of the array is not specified; each view using it may have a different data type. Below is an example code. Is it possible to access data from the array using an index? Every time I refresh, I get an "index out of range" error. import SwiftUI struct ContentView: View { @StateObject var viewModel = ViewModel() var body: some View { ScrollView { if !viewModel.testValues.isEmpty { LazyVStack(spacing: 20) { ForEach(Array(zip(viewModel.testValues.indices, viewModel.testValues)), id:\.1) { index, data in test(index: index, data: data, viewModel: viewModel) .onAppear { if !viewModel.isLoading, viewModel.testValues.count - 2 == index { viewModel.fetch() } } } } } else { Text("tesetsetsetsettse") } } .onAppear { viewModel.fetch() } .refreshable { viewModel.refresh() } } } struct test: View { let index: Int let data: String @ObservedObject var viewModel: ViewModel var body: some View { VStack(spacing: 8) { test1(index: index, data: data, viewModel: viewModel) Text("------------------------") } } } struct test1: View { let index: Int let data: String @ObservedObject var viewModel: ViewModel var body: some View { VStack { Text(viewModel.testValues[index]) .font(.system(size: 12)) .foregroundStyle(Color.red) .padding(.horizontal, 40) .padding(.vertical, 50) .background { RoundedRectangle(cornerRadius: 20) .fill(Color.blue) } } } } class ViewModel: ObservableObject { @Published var isLoading = false @Published var testValues: [String] = [] func fetch() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.testValues += [ UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, UUID().uuidString, ] } } func refresh() { testValues = [] fetch() } }
Posted
by HansolEom.
Last updated
.
Post not yet marked as solved
7 Replies
3.1k Views
The Build for Previews builds all my targets including the test targets. Is there a way to configure the relevant targets? I do not see an option in the schema editor, and disabling Find Implicit Dependencies has no effect either.
Posted
by chkpnt.
Last updated
.