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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

protocol in swiftUI
I've been reading the documentation and apparently protocols force structures, classes or enumerations to implement specific methods or define certain variables. I've double checked this functionality by typing the following code. In fact, xcode compiler helped me to verify this since it popped up an alert that depicted the following message : "Type MiguelStruc does not conform to protocol Miguels ..." protocol Miguels { func someF()-> Float } public struct MiguelStruc{ var miguelVar : String = "hey" } extension MiguelStruc: Miguels{ } Now, while I was following the official swiftUI drawing paths and shapes tutorial I encountered this particular chain of code: (https://developer.apple.com/tutorials/swiftui/drawing-paths-and-shapes) Path { path in } .fill(.black) By diving into the Swiftui documentation I noticed that Shape is a protocol public protocol Shape : Sendable, Animatable, View which is implemented by the Path structure extension Path : Shape Why none of the Path extensions content are explicitly implementing any of the Shape protocol requirements? such as role, layoutDirectionBehavior, sizeThatFits, offset, intersection, union, and so on!
4
0
178
3d
SwiftUI Trap change of orientation
The real truth is that I don't know what I am doing. I am trying to trap the change of orientation event. I have been strongly advised to use "Size Classes" rather than "Landscape" or "Portrait". Apparently, this is what Apple recommends. I have tried two or three ways to do this, and my closest effort to get it working has run me into an Issue (code below) that I don't know how to solve. I believe I have to use the @Evinroment macros to pick up the current size classes (@Environment(\.horizontalSizeClas) var .... and @Environment(\.verticalSizeClass) var ....) and these have to go inside a "View", I think. But I know when I get to setting up the Notification Center I will have to use the @Published macro to pass the orientation value back to my main "ContentView", again I think. And the @Published macro needs to run in a class. So I have tried to put a "View" inside a "class" and run into an issue that the @Pulished variable (a String) is only recognised in the "class" and the size classes are only recognised in the "View". So How do I overcome this? Here is the Code I have come up with so far, it is incomplete and when I get this working I will add more. import SwiftUI final class OrientChange { @Published public var myOrient: String init(myOrient: String){ self.myOrient = myOrient } struct SizeClassView: View { @Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass? @Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass? var body: some View { Text("Horiz Class: \(myHorizClass)") if myHorizClass == .compact && myVertClass == .regular { OrientChange.myOrient = "Portrait" } else { Text("No") } } } } #Preview { OrientChange.SizeClassView() }
2
0
162
5d
SwiftUI Orientation Change
I have been struggling for nearly a week to handle orientation changes. In a previous post https://developer.apple.com/forums/thread/755957 I was strongly advised to use Size Classes, and I am trying to do that. by following this post: https://forums.developer.apple.com/forums/thread/126878) But I still can get it to work, so far I am just trying to initialize all the variables I will use later on. please bear with me I am 65 and have not done any coding for coming for 40 years. This my latest effort: import SwiftUI final class myOrientationChange: ObservableObject { @Published var myOrient: String = "" @Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass? @Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass? var _observer: NSObjectProtocol? if myHorizClass == .compact && myVertClass == .regular { self.myOrient = "Portrait" } elseif myHorizClass == .regular && myVertClass == .compact { self.myOrient = "Landscape" } else { self.myOrient = "Something Else" } } struct ContentView: View { @EnvironmentObject var envOrient: myOrientationChange var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Text("Orientation is \(envOrient.myOrient)") } .padding() } } #Preview { ContentView() } I will go on to use the NotificationCenter to trap there change of orientation even. On the line if myHorizClass == ......... It tells me "Expected declaration in declaration of 'myOrientChange'" What have I done wrong?
1
0
173
6d
View is not updating by adding or deleting an item
When I parse the query result(SwiftData) to my DetailView it works fine. But when I delete the item in the DetailView the view isn't updated. I parse the array from the dataModel to the DetailView. But I do not understand why it's not updating when I add or delete a tree in the DetailView. Only when I append the tree to the array from the other model after insert it works. Does someone have a tip for me? Here is my Code: https://gist.github.com/romanindermuehle/14441c21f689e91b26942d997f75300d
0
0
136
6d
How to get GeoLocation from a driver's phone
I need to build SwiftUI app to calculate a distance between my current location and my driver's real-time location. All the drivers' phones will be asked to enable location service when they are in use of this app. So what I wanted is to get a real-time Longitude and Latitude for a given driver's phone number that registered in this app.
2
0
205
6d
Picker from the toolbar in watchOS (SwiftUI)
What I'm trying to do is to display a picker in watchOS: this picker will have only 4 options, so I would like it to be in the style of .navigationLink. Currently I have this code inside a view and everything works fine (DateRange is an enum): Picker(selection: $dateRange) { Text("Today").tag(DateRange.today) Text("This week").tag(DateRange.thisWeek) Text("Last 7 days").tag(DateRange.lastSevenDays) Text("Last 30 days").tag(DateRange.lastThirtyDays) } label: { Image(systemName: "line.3.horizontal.decrease.circle") } .pickerStyle(.navigationLink) What I'd like to do is to move this picker to the toolbar: I've seen that by wrapping it in a ToolbarItem everything works, but the current selection is displayed in the toolbar button, and this breaks the layout (the string doesn't fit). Moreover, when the picker appears from the toolbar the options still work, but are grayed out, as if they were disabled. Is there a way to have a picker appear when clicking on a toolbar item, but not showing the selection and being "enabled"?
0
0
125
6d
"Unexpectedly found nil while unwrapping an Optional value" in URL
Before anyone rants and raves about checking documentation - I have spent the last 4 hours trying to solve this issue on my own before asking for help. Coding in Swift is VERY new for me and I'm banging my head against the wall trying to teach myself. I am very humbly asking for help. If you refer me to documentation, that's fine but I need examples or it's going to go right over my head. Teaching myself is hard, please don't make it more difficult. I have ONE swift file with everything in it. import Foundation import Cocoa import Observation class GlobalString: ObservableObject { @Published var apiKey = "" @Published var link = "" } struct ContentView: View { @EnvironmentObject var globalString: GlobalString var body: some View { Form { Section(header: Text("WallTaker for macOS").font(.title)) { TextField( "Link ID:", text: $globalString.link ) .disableAutocorrection(true) TextField( "API Key:", text: $globalString.apiKey ) .disableAutocorrection(true) Button("Take My Wallpaper!") { } } .padding() } .task { await Wallpaper().fetchLink() } } } @main struct WallTaker_for_macOSApp: App { @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true @EnvironmentObject var globalString: GlobalString var body: some Scene { WindowGroup { ContentView() .environmentObject(GlobalString()) } // MenuBarExtra("WallTaker for macOS", systemImage: "WarrenHead.png", isInserted: $showMenuBarExtra) { // Button("Refresh") { //// currentNumber = "1" // } // Button("Love It!") { //// currentNumber = "2" // } // Button("Hate It!") { //// currentNumber = "3" // } // Button("EXPLOSION!") { // // currentNumber = "3" // } //// // } } } class Wallpaper { var url: URL? = nil var lastPostUrl: URL? = nil let mainMonitor: NSScreen init() { mainMonitor = NSScreen.main! } struct LinkResponse: Codable { var post_url: String? var set_by: String? var updated_at: String } struct Link { var postUrl: URL? var setBy: String var updatedAt: Date } func parseIsoDate(timestamp: String) -> Date? { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter.date(from: timestamp) } func fetchLink() async { do { url = URL(string: GlobalString().link) let (data, _) = try await URLSession.shared.data(from: url!) let decoder = JSONDecoder() let linkResponse = try decoder.decode(LinkResponse.self, from: data) let postUrl: URL? = linkResponse.post_url != nil ? URL(string: linkResponse.post_url!) : nil let date = parseIsoDate(timestamp: linkResponse.updated_at) let link = Link( postUrl: postUrl, setBy: linkResponse.set_by ?? "anon", updatedAt: date ?? Date() ) try update(link: link) } catch { } } func update(link: Link) throws { guard let newPostUrl = link.postUrl else { return } if (newPostUrl != lastPostUrl) { lastPostUrl = newPostUrl let tempFilePath = try getTempFilePath() try downloadImageTo(sourceURL: newPostUrl, destinationURL: tempFilePath) try applyWallpaper(url: tempFilePath) } else { } } private func applyWallpaper(url: URL) throws { try NSWorkspace.shared.setDesktopImageURL(url, for: mainMonitor, options: [:]) } private func getTempFilePath() throws -> URL { let directory = NSTemporaryDirectory() let fileName = NSUUID().uuidString let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])! return fullURL } private func downloadImageTo(sourceURL: URL, destinationURL: URL) throws { let data = try Data(contentsOf: sourceURL) try data.write(to: destinationURL) } } The 'fetchLink' function is where things explode, specifically when setting the URL. I do not know what I'm doing wrong.
3
0
201
1w
View update issues + DisclosureGroup issue
My code was working perfectly well until the latest Xcode update. Suddenly the DisclosureGroup stopped working, causing the app to freeze. Also there seems to have been a change to the way SwiftUI tracks view updates because some of my code went into a screaming loop thinking a view was constantly changing. Developing code is hard enough without these problems coming out of nowhere.
1
0
104
1w
How to get selected usdz model thumbnail image using QuickLookThumbnailing
I am doing below code for getting thumbnail from usdz model using the QuickLookThumbnailing, But don't get the proper out. guard let url = Bundle.main.url(forResource: resource, withExtension: withExtension) else{ print("Unable to create url for resource.") return } let request = QLThumbnailGenerator.Request(fileAt: url, size: size, scale: 10.0, representationTypes: .all) let generator = QLThumbnailGenerator.shared generator.generateRepresentations(for: request) { thumbnail, type, error in DispatchQueue.main.async { if thumbnail == nil || error != nil { print(error) }else{ let tempImage = Image(uiImage: thumbnail!.uiImage) print(tempImage) self.thumbnailImage = Image(uiImage: thumbnail!.uiImage) print("=============") } } } } Below Screen Shot for selected model : Below is the thumbnail image, which not come with guitar but get only usdz icon.
1
0
138
1w
glassMaterialEffect not working in immersive view with a skybox
I seem to be running into an issue where the .glassBackgroundEffect modifier doesn't seem to render correctly. The issue is occurring when attached to a view shown in a RealityKit immersive view with a Skybox texture. The glass effect is applied but doesn't let any of the colour of the skybox behind it though. I have created a sample project which is just the immersive space template with the addition of a skybox texture and an attachment with the glassBackgroundEffect modifier. The RealityView itself is struct ImmersiveView: View { var body: some View { RealityView { content, attachments in // Add the initial RealityKit content if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) { content.add(immersiveContentEntity) let attachment = attachments.entity(for: "foo")! let leftSphere = immersiveContentEntity.findEntity(named: "Sphere_Left")! attachment.position = [0, 0.2, 0] leftSphere.addChild(attachment) // Add an ImageBasedLight for the immersive content guard let resource = try? await EnvironmentResource(named: "ImageBasedLight") else { return } let iblComponent = ImageBasedLightComponent(source: .single(resource), intensityExponent: 0.25) immersiveContentEntity.components.set(iblComponent) immersiveContentEntity.components.set(ImageBasedLightReceiverComponent(imageBasedLight: immersiveContentEntity)) // Put skybox here. See example in World project available at var skyboxMaterial = UnlitMaterial() let skyboxTexture = try! await TextureResource(named: "pano") skyboxMaterial.color = .init(texture: .init(skyboxTexture)) let skyboxEntity = Entity() skyboxEntity.components.set(ModelComponent(mesh: .generateSphere(radius: 1000), materials: [skyboxMaterial])) skyboxEntity.scale *= .init(x: -1, y: 1, z: 1) content.add(skyboxEntity) } } update: { _, _ in } attachments: { Attachment(id: "foo") { Text("Hello") .font(.extraLargeTitle) .padding(48) .glassBackgroundEffect() } } } } The effect is shown bellow I've tried this both in the simulator and in a physical device and get the same behaviour. Not sure if this is an issue with RealityKit or if I'm just holding it wrong, would greatly appreciate any help. Thanks.
1
0
162
1w
SwiftUI `onOpenURL` lacks `referrerURL` and `annotation` present in NSUserActivity
Hello, I am working on an application that utilizes both AppDelegate and SceneDelegate. We are looking to convert the top level app to SwiftUI and start using the SwiftUI App lifecycle. When implementing, I see that deep links when the app is backgrounded will only route to the onOpenURL modifier. This means that information we relied on before like referrerURL and annotation present in the NSUserActivity object delivered to the app is no longer available. Is there any work around for this? It seems like missing functionality because there is no way to route the deep links through AppDelegate or SceneDelegate if you are using the SwiftUI App protocol.
1
0
131
1w
SwiftUI Previews that work in Xcode 15.2 now fail in Xcode 15.3 with failedToGenerateThunkInfo error
I have a Swift Package Manager module with some SwiftUI files that I was using Previews without issues in Xcode 15.2. When I upgraded to Xcode 15.3, it fails with “Cannot preview in this file. Unexpected error occurred”. When I click to get more info, this is the error: == PREVIEW UPDATE ERROR: HumanReadableSwiftError BuildError: failedToGenerateThunkInfo(could not generate preview info: noTargetBuildGraph) Is anyone experiencing the same problems? My preview, which lives in a SPM package, works totally fine in Xcode 15.2, but fails in Xcode 15.3. Any ideas for how to fix it? I've tried deleting DerivedData, resetting package caches, clean building. So frustrating seeing these regression issues popping up still. I filed FB13678356 but it was quickly marked as "Investigation Complete - Unable to diagnose with current information" but there was no request for what further information I could provide! I attached a full sysdiagnose and error log! Would also note, that when I revert back to Xcode 15.2, the previews go back to working...
9
0
969
1w
Apple activity ring(sparkle)
Hello everyone My goal is to create Apple's activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a sparkle effect, but I don't know how to modify it to achieve my goal. Because I'm pretty new to SwiftUI animations. Does anyone have any idea how I could do this? Vortex project: https://github.com/twostraws/Vortex
2
0
211
1w
Get Touch Events from iOS keyboard trackpad mode
Hello, As of iOS 17, the keyboard app runs in a different process. I was wondering if there is a way to access the UIView of the keyboard app or if there is a way to subscribe to touch events done on the keyboard (especially during the trackpad mode). By trackpad mode I mean when the user long presses on space and then can move in the keyboard area (that turns into a trackpad) to move the caret in a text. Either Objective C or SwiftUI is fine. Thanks!
1
0
134
1w
Problem with NavigationStack(path:)
Hello everyone. I am developing an application with SwiftUI. I am having trouble with NavigationStack(path: ). 1st problem: After the application runs, after clicking on the first list item, there is a flicker in the title section. I think it is the .navigationDestination that causes this problem, because when I change the navigationLink to Button in the “ActiveRegQueryView” screen, this problem disappears. 2nd Problem: When you click on a list item, sometimes it stays pressed (grayed out) and does not take you to the screen (Video 1). If you try to click on an item more than once, navigatinLink passes more than one value to path and opens more than one page (I noticed this with path.count) (Video 2). I don't have this problem if you edit the back button on the screen it takes you to (ActiveRegDetailView). (vm.path.removeLast()) The reason I use path is to close multiple screens and return to the start screen. Video 1: Video 2: Main View: import SwiftUI struct ActiveRegView: View { @Environment(NavigationViewModel.self) private var navViewModel @AppStorage("sortOption") private var sortOrder: sorting = .byBrand @State private var searchText = "" var body: some View { @Bindable var navViewModel = navViewModel NavigationStack(path: $navViewModel.path) { // <- if i don't use path everything is OK List { ActiveRegQueryView(searchText: searchText, sortOrder: sortOrder) // <- Dynamic Query View } .navigationDestination(for: Registration.self, destination: { ActiveRegDetailView(reg: $0) .toolbar(.hidden, for: .tabBar) }) } } } Dynamic Query View: import SwiftData import SwiftUI struct ActiveRegQueryView: View { @Query private var regs: [Registration] @Environment(NavigationViewModel.self) var vm init(searchText: String, sortOrder: sorting) { var order: SortDescriptor<Registration> switch sortOrder { case .byBrand: order = SortDescriptor(\.brand) case .byDateDescending: order = SortDescriptor(\.entryRegistration.entryDate, order: .reverse) case .byDateAscending: order = SortDescriptor(\.entryRegistration.entryDate) } _regs = Query(filter: #Predicate { if !searchText.isEmpty { if $0.activeRegistration && ($0.brand.localizedStandardContains(searchText) || $0.model.localizedStandardContains(searchText) || $0.plate.localizedStandardContains(searchText)) { return true } else { return false } } else { return $0.activeRegistration } }, sort: [order]) } var body: some View { ForEach(regs) { reg in NavigationLink(value: reg) { ListRowView(reg: reg) } // Button { // vm.path.append(reg) // } label: { // ListRowView(reg: reg) // } // .buttonStyle(.plain) } } } I look forward to your ideas for solutions. Thank you for your time.
0
0
162
1w
SwiftUI: How do I tell when my device orientation changes
Sorry to repeat this, but the new style forum won't allow me access to the original version of this question, and the answers. I have been searching the internet for 3 or 4 days now to find only complex solutions that I cannot get working. All I want to do is determine when the device orientation changes so that I can update the background Image. This is what I have so far: Import SwiftUI struct Main_Menu_iPhone: View { @State private var bloodGlucose: Float = 0.0 var body: some View { ZStack { Image("iPhone Background Portrait 828 x 1792 ") .resizable() .aspectRatio(contentMode: .fill) VStack { HStack { Label("Blood Glucose", systemImage: "drop.fill") TextField("Blood Glucose : ", value: $bloodGlucose, format: .number) .onSubmit() { print("Your Blood Gluse is : \(bloodGlucose)") } .background(.white) .frame(alignment: .topTrailing) Spacer() } Spacer() }.padding(.top, 250) } } }
1
0
303
1w
Why can't I get text to appear at top of view.
No matter what I have tried, I can't get my test "What would you like to do?" to appear at the top of the screen. What have I missed? Is something g to do with the ZStack? import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var context @Query private var readings: [Readings] @State private var readingTimeStamp: Date = Date() var body: some View { ZStack { Image("IPhone baqckgound 3") .resizable() .aspectRatio(contentMode: .fill) .padding(.top, 40) VStack { Text("What would you like to do?") .font(.title) .fontWeight(.bold) } .padding() Spacer() } } }
3
0
163
1w
EnvironmentObject Causes SwiftUI App to Crash When Launched in the Background
I recently encountered a difficult-to-diagnose bug in an app that I'm working on, and I thought I would share it with the Apple Developer community. The app that I'm working on is an iOS app that uses Core Location's Visit Monitoring API, and it is essential that the app is able to process incoming visits while running in the background. However, after real-world testing, I discovered several crash reports which were difficult to understand, as SwiftUI symbols are not symbolicated on debug builds. Eventually I discovered that the app was crashing when calling an @EnvironmentObject property of the root ContentView from that view's body when the app was launched directly into the background from not running at all. After creating a small test app to isolate the problem, I discovered that any environment object declared in the App struct and referenced from the root ContentView causes the crash, with the exception message: "Fatal error: No ObservableObject of type ArbitraryEnvObject found. A View.environmentObject(_:) for ArbitraryEnvObject may be missing as an ancestor of this view." It seems that when a SwiftUI app is launched in the background, the ContentView's body is executed, but the environment is not initialized. I searched through as much documentation as I could, but could not find any information about how this should be handled, so I think it's a bug in SwiftUI. I have filed a Feedback Assistant bug report. The current workaround is to convert my ObservableObject into an object that conforms to the new @Observable protocol, add it to the scene as an Environment Value with the .environment(_:) modifier rather than the .environmentObject(_:) modifier, and declare the @Environment property on the view as optional. The object will still be missing when the app is launched in the background, but the optional property can be handled safely to prevent a crash. Attached to this post is a sample project that demonstrates the issue and the workaround. And finally, I'd like to hear from anyone who knows more about the expected behavior of background launches of SwiftUI apps, and whether or not there's something I should be doing completely differently. I'm not able to directly attach a zip archive to this post, so here's an iCloud link to the sample project: BackgroundEnvObjCrash.zip
5
1
786
1w
Core Animation Layer in SwiftUI app does not update unless I rotate the device.
I am trying to create a near real-time drawing of waveform data from within a SwiftUI app. The data is streaming in from the hardware and I've verified that the draw(in ctx: CGContext) override in my custom CALayer is getting called. I have added this custom CALayer class as a sublayer to a UIView instance that I am making available via the UIViewRepresentable protocol. The only time I see updated output from the CALayer is when I rotate the device and layout happens (I assume). How can I force SwiftUI to update every time I render new data in my CALayer? More Info: I'm porting an app from the Windows desktop. Previously, I tried to make this work by simply generating a new UIImage from a CGContext every time I wanted to update the display. I quickly exhausted memory with that technique because a new context is being created every time I call UIGraphicsImageRenderer(size:).image { context in }. What I really wanted was something equivalent to a GDI WritableBitmap. Apparently this animal allows a programmer to continuously update and re-use the contents. I could not figure out how to do this in Swift without dropping down to the old CGBitmapContext stuff written in C and even then I wasn't sure if that would give me a reusable context that I could output in SwiftUI each time I refreshed it. CALayer seemed like the answer. I welcome any feedback on a better way to do what I'm trying to accomplish.
2
0
247
1w