Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Strange visionOS Simulator
I found that my visionOS Simulator is very strange. Many functions and features are missing. For example, I learned from the Internet that the immersive scenes of Environments in their visionOS Simulator can be opened, but I click There was no response after the attack. There are not only these, but also many system features. I saw on the Internet that other developers have them, and I am missing. I'm worried that this will have an impact on me when testing my app. May I ask why? Some information: My updated Xcode version is the latest Xcode15.1Beta. Device: iMac (2021) Simulator system number: 21N305
1
0
551
Jan ’24
Swift Cocoa: PrintOperation() with Sonoma does not work
I have a Swift Coco program taht print a NSView. It work perfectly fine in Monterey but does show the print panel in Sonoma. I cannot find the problem. Here are the 4 errors: Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable Failed to connect (otherPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (localPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable func createPrintOperation() { let printOpts: [NSPrintInfo.AttributeKey: Any] = [ .headerAndFooter: false, .orientation: NSPrintInfo.PaperOrientation.portrait ] let printInfo = NSPrintInfo(dictionary: printOpts) printInfo.leftMargin = 0 printInfo.rightMargin = 0 printInfo.topMargin = 0 printInfo.bottomMargin = 0 printInfo.horizontalPagination = .fit printInfo.verticalPagination = .automatic printInfo.isHorizontallyCentered = true printInfo.isVerticallyCentered = true printInfo.scalingFactor = 1.0 printInfo.paperSize = NSMakeSize(612, 792) // Letter size // Create a print operation with the view you want to print , myPrintView is a NSView let printOperation = NSPrintOperation(view: myPrintView, printInfo: printInfo) // Configure the print panel printOperation.printPanel.options.insert(NSPrintPanel.Options.showsPaperSize) printOperation.printPanel.options.insert(NSPrintPanel.Options.showsOrientation) // Set the job title for the print operation let jobTitle = fact.nom_complet_f.replacingOccurrences(of: " ", with: "") printOperation.jobTitle = jobTitle // Run the print operation printOperation.run() }
2
0
227
Aug ’24
Implement UNUserNotificationCenterDelegate in iOS app using Swift6
I've got a problem with compatibility with Swift6 in iOS app that I have no idea how to sort it out. That is an extract from my main app file @MainActor @main struct LangpadApp: App { ... @State private var notificationDataProvider = NotificationDataProvider() @UIApplicationDelegateAdaptor(NotificationServiceDelegate.self) var notificationServiceDelegate var body: some Scene { WindowGroup { TabView(selection: $tabSelection) { ... } .onChange(of: notificationDataProvider.dateId) { oldValue, newValue in if !notificationDataProvider.dateId.isEmpty { tabSelection = 4 } } } } init() { notificationServiceDelegate.notificationDataProvider = notificationDataProvider } } and the following code shows other classes @MainActor final class NotificationServiceDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var notificationDataProvider: NotificationDataProvider? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self return true } func setDateId(dateId: String) { if let notificationDataProvider = notificationDataProvider { notificationDataProvider.dateId = dateId } } nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { // After user pressed notification let content = response.notification.request.content if let dateId = content.userInfo["dateId"] as? String { await MainActor.run { setDateId(dateId: dateId) } } } nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { // Before notification is to be shown return [.sound, .badge, .banner, .list] } } @Observable final public class NotificationDataProvider : Sendable { public var dateId = "" } I have set Strict Concurrency Checking to 'Complete.' The issue I'm facing is related to the delegate class method, which is invoked after the user presses the notification. Current state causes crash after pressing notification. If I remove "nonisolated" keyword it works fine but I get the following warning Non-sendable type 'UNNotificationResponse' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'userNotificationCenter(_:didReceive:)' cannot cross actor boundary; this is an error in the Swift 6 language mode I have no idea how to make it Swift6 compatible. Does anyone have any clues?
0
9
505
Aug ’24
AppStorage extension for Bool Arrays
Hi, As AppStorage does not support arrays, I found an extension online that allows for handling arrays of strings with AppStorage. However, in my use case, I need to handle arrays of boolean values. Below is the code. Any help would be greatly appreciated. extension Array: RawRepresentable where Element: Codable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode([Element].self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), let result = String(data: data, encoding: .utf8) else { return "[]" } return result } }
1
0
307
Aug ’24
[WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. What does this mean?
Getting this error several times when presenting a modal window over my splitview window when running it on my Mac using Swift/Mac Catalyst in XCode 14.2. When I click the Cancel button in the window then I get Scene destruction request failed with error: (null) right after an unwind segue. 2023-07-04 16:50:45.488538-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.488972-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496702-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496800-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.994147-0500 Recipes[27836:1295134] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7f7fdf068a00>. bleep 2023-07-04 16:51:00.655233-0500 Recipes[27836:1297298] Scene destruction request failed with error: (null) I don't quite understand what all all this means. (The "bleep" was a debugging print code I put in the unwind segue). I'm working through Apple's Mac Catalyst tutorial but it seems to be riddled with bugs and coding issues, even in the final part of the completed app which I dowmloaded and ran. I don't see these problems on IPad simulator. I don't know if it's because Catalyst has problems itself or there's something else going on that I can fix myself. Any insight into these errors would be very much appreciated! PS: The app seems to run ok on Mac without crashing despite the muliple issues
4
3
1.4k
Jul ’23
Sign in with Apple button dark mode in Swift
I implemented Sign in with Apple but in all cases the button is always black. I would like to show it in light/ dark mode depending on the phone settings. This is my code: class MyAuthorizationAppleIDButton: UIButton { private var authorizationButton: ASAuthorizationAppleIDButton! @IBInspectable var cornerRadius: CGFloat = 3.0 @IBInspectable var authButtonType: Int = ASAuthorizationAppleIDButton.ButtonType.default.rawValue @IBInspectable var authButtonStyle: Int = ASAuthorizationAppleIDButton.Style.black.rawValue override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func draw(_ rect: CGRect) { super.draw(rect) // Create ASAuthorizationAppleIDButton authorizationButton = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black) let type = ASAuthorizationAppleIDButton.ButtonType.init(rawValue: authButtonType) ?? .default let style = ASAuthorizationAppleIDButton.Style.init(rawValue: authButtonStyle) ?? .black authorizationButton = ASAuthorizationAppleIDButton(authorizationButtonType: type, authorizationButtonStyle: style) authorizationButton.cornerRadius = cornerRadius // Show authorizationButton addSubview(authorizationButton) // Use auto layout to make authorizationButton follow the MyAuthorizationAppleIDButton's dimension authorizationButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ authorizationButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0), authorizationButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0.0), authorizationButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0.0), authorizationButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0), ]) } } So basically with the code above, I can set on Storyboard the style of the button but it seems that even if I change the value at my code, the result is based on what I chose on Storyboard's variable. Is there any solution where I would be able to show the button in light/ dark mode depending on the phone settings ?
2
1
929
Jul ’23
Interface fails to work because I have a class named Context.
Bug When you try to extend from NSViewRepresentable but you have a class named Context swift throws a error message that doesn't help at all. Type 'MetalViewRepresentable' does not conform to protocol 'NSViewRepresentable' Steps to reproduce Create a MacOS App Copy this code struct MetalViewRepresentable: NSViewRepresentable { @Binding var metalView: MTKView func makeNSView(context: Context) -> some NSView { metalView } func updateNSView(_ uiView: NSViewType, context: Context) { } } Write this line of code in any file class Context {}
0
0
206
Aug ’24
Swift Package Manager not building external dependencies correctly
I have created my own SPM through File -> New -> Package Package.swift looks like: // swift-tools-version: 5.10 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "MyPackage", platforms: [.iOS(.v16), .macCatalyst(.v16), .macOS(.v14)], products: [.library(name: "MyPackage", targets: ["MyPackage"]),], dependencies: [ .package(path: "../external-package") ], targets: [ .target(name: "MyPackage", path: "Sources"), .testTarget(name: "MyPackageTests", dependencies: ["MyPackage"]), ] ) When I run swift build the error says: '.../MyPackage/.build/arm64-apple-macosx/debug/external-package.build/external-package-Swift.h' not found and surely, when I go to directory: .../MyPackage/.build/arm64-apple-macosx/debug/external-package.build/ there are only 2 files in there: module.modulemap & output-file-map.json All source files from external-package are missing, therefore swift build fails. The only solution I've found is to copy external-package.build folder manually into: '.../MyPackage/.build/arm64-apple-macosx/debug/` What am I missing here? Should swift build create those files in there, or they should be resolved somehow differently? Note: external-package is not in any way unique, this happens to any added dependency I'm running on macOS 14.6.1 on Apple Silicon M1 Pro with Xcode 15.4
1
0
404
Aug ’24
How does the threshold in DeviceActivityEvent work
Hey everyone, I'm working on implementing an AppLimit, where after accumulating x minutes of Screen Time for an app, it should be blocked. It works fine on the first day, but stops functioning correctly on subsequent days. What I'm Doing I start a 24/7 schedule with a DeviceActivityEvent that has a specified Screen Time threshold. In my DeviceActivityMonitor, I'm reacting to the eventDidReachThreshold. Once the accumulated time is reached, the app is blocked. This works as expected on the first day. Issues I'm Experiencing / Questions Second Day Issue: On the second day, the app is no longer blocked after the Screen Time threshold is reached, even though it worked on the first day. This leads me to suspect that a DeviceActivityEvent is "consumable". Is this correct? Pre-existing Screen Time Issue: If a user has already surpassed the Screen Time threshold before monitoring starts, the app isn't blocked once the schedule is set up. This leads to 2 issues: I would expect that the accumulated amount of time after starting the schedule would result in the call of eventDidReachThreshold. But it is never called It could also be the case that the previously accumulated time is being kept in mind, but that would mean the apps should be blocked, which isn't the case. Does the threshold account for accumulated Screen Time before the schedule begins? I haven't tested setting a limit of 10 minutes, accumulating 3 minutes of Screen Time, then starting the schedule and accumulating the remaining time, but I'm curious if anyone has encountered this behavior. Does anyone have an explanation for this behavior? Any help would be greatly appreciated!
1
0
417
Aug ’24
MDM - Getting location when app is killed
Dear, We are working on a solution that uses MDM to manage devices and create features for our users. As part of this, we want to implement a feature that retrieves the device's location even when the app is closed (killed). Is there a way to achieve this? Since we are an MDM solution, is there a function available within MDM that allows us to obtain this information? We are considering implementing the Location Push Service Extension. If we do, will we be able to receive latitude and longitude even if the app is closed?
0
0
192
Aug ’24
Condensing HTTP request functions
Hi, For HTTP requests, I have the following function: func createAccount(account: Account, completion: @escaping (Response) -> Void) { guard let url = URL(string: "http://localhost:4300/account") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") guard let encoded = try? JSONEncoder().encode(account) else { print("Failed to encode request") return } request.httpBody = encoded URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { let resData = try JSONDecoder().decode(Response, from: data) DispatchQueue.main.async { completion(resData) } } catch let jsonError as NSError { print("JSON decode failed: \(jsonError)") } }.resume() } Because various HTTP requests use different body structs and response structs, I have a HTTP request function for each individual HTTP request. How can I condense this into one function, where the passed struct and return struct are varying, so I can perhaps pass the struct types in addition to the data to the function? Any guidance would be greatly appreciated.
0
0
213
Aug ’24
Build iOS 18 with Swift 5.10
I noticed that running my app in Xcode 16 crashes often. It seems this is due to the strictness Swift 6 adds at runtime. Even after making sure the Swift Language Mode is 5 for the main target and all modules. I'm migrating to Swift 6 but I probably won't be done before iOS 18 drops so my question is. Can I still ship the app supporting iOS 18 using Xcode 15.4 and Swift 5.10?
2
1
504
Aug ’24
IOS 18 Public Beta issues
I can’t merge phone calls, people on the phone cannot hear meand I can’t hear them Alarm doesn’t work sound sometimes. I need to reboot the phone to make sure it works I need to reboot the phone to make sure it works 3. Cannot update customize wallpaper for home screen. You can update lock screen but not home screen. You can update lock screen but not home screen.
1
0
177
Aug ’24
Polar H10 ECG reading
There are some reliable and affordable Polar H10 ECG reader apps available on the App Store: I’ve been using one for a couple of years. However, I recently needed to incorporate an ECG capability into an app that already uses the Polar H10 for RR Interval monitoring, but the documentation online for Polar ECG is scarce and sometimes incorrect. Polar provides an SDK, but this covers many different devices and so is quite complex. Also, it’s based on RxSwift - which I prefer not to use given that my existing app uses native Swift async and concurrency approaches. I therefore offer this description of my solution in the hope that it helps someone, somewhere, sometime. The Polar H10 transmits ECG data via Bluetooth LE as a stream of frames. Each frame is length 229 bytes, with a 10 byte leader and then 73 ECG data points of 3 bytes each (microvolts as little-endian integer, two’s complement negatives). The leader’s byte 0 is 0x00, bytes 1 - 8 are a timestamp (unknown epoch) and byte 9 is 0x00. The H10’s sampling rate is 130Hz (my 2 devices are a tiny fraction higher), which means that each frame is transmitted approximately every half second (73/130). However, given the latencies of bluetooth transmission and the app’s processing, any application of a timestamp to each data point should be based on a fixed time interval between each data point, i.e. milliseconds interval = 1000 / actual sampling rate. From my testing, the time interval between successive frame timestamps is constant and so the actual sampling interval is that interval divided by 73 (the number of samples per frame). I’ve noticed, with both the 3rd party app and my own coding, that for about a second (sometimes more) the reported voltages are very high or low before settling to “normal” oscillation around the isoelectric line. This is especially true when the sensor electrode strap has only just been placed on the chest. To help overcome this, I use the Heart Rate service UUID “180D” and set notify on characteristic "2A37" to get the heart rate and RR interval data, of which the first byte contains flags including a sensor contact flag (2 bits - both set when sensor contact is OK, upon which I setNotifyValue on the ECG data characteristic to start frame delivery). Having discovered your Polar H10, connected to it and discovered its services you need to discover the PMD Control Characteristic within the PMD Service then use it to request Streaming and to request the ECG stream (there are other streams). Once the requests have been accepted (didWriteValueFor Characteristic) then you start the Stream. Thereafter, frames are delivered by the delegate callback func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) for the characteristic.uuid == pmdDataUUID The following code snippets, the key aspects of the solution, assume a working knowledge of CoreBluetooth. Also, decoding of data (code not provided) requires a knowledge of byte and bit-wise operations in Swift (or Objective-C). // CBUUIDs and command data let pmdServiceUUID = CBUUID.init( string:"FB005C80-02E7-F387-1CAD-8ACD2D8DF0C8" ) let pmdControlUUID = CBUUID.init( string:"FB005C81-02E7-F387-1CAD-8ACD2D8DF0C8" ) let pmdDataUUID = CBUUID.init( string:"FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8" ) let reqStream = Data([0x01,0x02]) let reqECG = Data([0x01,0x00]) let startStream = Data([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00]) // Request streaming of ECG data func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) if service.uuid == pmdServiceUUID { for pmdChar in service.characteristics! { if pmdChar.uuid == pmdControlUUID { peripheral.setNotifyValue(true, for: pmdChar) peripheral.writeValue(reqStream, for: pmdChar, type: .withResponse) peripheral.writeValue(reqECG, for: pmdChar, type: .withResponse) } } } } // Request delivery of ECG frames - actual delivery subject to setNotify value func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { // this responds to the reqStream and reqECG write values if error != nil { print("**** write error") return } if ecgStreamStarted { return } // I use a flag to prevent extraneous stream start commands guard let charVal = characteristic.value else { return } if charVal[0] == 0xF0 && charVal[1] == 0x01 { peripheral.writeValue(startStream, for: characteristic, type: .withResponse) ecgStreamStarted = true } } For “live” charting, I create an array of data points, appending each frame’s set on arrival, then provide those points to a SwiftUI View with a TimeLineView(.periodic(from: .now, by:actual sampling interval)) and using Path .addlines with the Y value scaled appropriately using GeometryReader. So far, I’ve found no way of cancelling such a TimeLineView period, so any suggestions are welcome on that one. An alternative approach is to refresh a SwiftUI Chart View on receipt and decoding of each frame, but this creates a stuttered appearance due to the approximately half-second interval between frames. Regards, Michaela
0
0
457
Aug ’24
Develop in Swift - SwiftUI update?
I've been relishing Develop in Swift: Fundamentals as an introduction to Swift. It's wonderful! Having limited time, and ultimately targeting visionOS development, I've reached a point where any UIKit content feels like a distraction from my goals. Hence I'm switching to SwiftUI Bootcamp by Swiftful Thinking on YouTube, SwiftUI Concepts Tutorials, and SwiftUI Tutorials by Apple. Is there any official word on updates to the Develop in Swift series? Failing that, any other recommendations on how to bridge between Fundamentals and visionOS development?
2
0
397
Aug ’24
Open specific web extension in safari settings (iOS/App/Swift)
Hi all, I have a problem with trying to use UIApplication.shared.canOpenURL to open a specific web extension in the safari settings. When executing the code below the safari extension menu is shown but not the settings for the specific extension: if let url = URL(string: "App-prefs:SAFARI&path=WEB_EXTENSIONS/NAME_OF_EXTENSION") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } However, the weird thing is that when executing the above I can see some kind of an event that looks like it tries to click the specific extension. Furthermore, if I keep the settings open and tries to execute the code again it actually works, and the specific web extension's settings is open. Hope someone can help.
0
0
289
Aug ’24
xCode Project with Breakpoints and .app Crashing?
I recently created a project, originally in xCode 13.3 if i am not miistaken. Then i update it to 13.4 then update to mac os 15.6 as well. Previously the project worked fine, but then i notice if i activate breakpoints the projects stopped when i run it in xCode but it worked fine like before, without breakpoints activated. Also, when i build a .app of the project, the .app crashed exactly when the breakpoints previously stopped. I am very confused on how to continue, would like to get help from anyone regarding the issue. From what i can gather from the breakpoints and crash report, it's got something about UUIID registration? AV foundation? I am so confused. Please Help! Thanks.
0
0
303
Aug ’24
ModelContainer working but ModelContext not finding items with SwiftDta
I am trying to count a database table from inside some of my classes. I am tying to do this below **(My problem is that count1 is working, but count2 is not working.) ** class AppState{ private(set) var context: ModelContext? .... func setModelContext(_ context: ModelContext) { self.context = context } @MainActor func count()async{ let container1 = try ModelContainer(for: Item.self) let descriptor = FetchDescriptor<Item>() let count1 = try container1.mainContext.fetchCount(descriptor) let count2 = try context.fetchCount(descriptor) print("WORKING COUNT: \(count1)") print("NOTWORKING COUNT: \(count2) -> always 0") } I am passing the context like: ... @main @MainActor struct myApp: App { @State private var appState = AppState() @Environment(\.modelContext) private var modelContext WindowGroup { ItemView(appState: appState) .task { appState.setModelContext(modelContext) } } .windowStyle(.plain) .windowResizability(.contentSize) .modelContainer(for: [Item.self, Category.self]) { result in ... } Can I get some guidance on why this is happening? Which one is better to use? If I should use count2, how can I fix it? Is this the correct way to search inside an application using SwiftData ? I don't wanna search using the View like @Query because this operation is gonna happen on the background of the app.
1
0
341
Aug ’24
Best way to pause DeviceActivitySchedule
Hi everyone, I'm currently working with the Screen Time API, specifically trying to figure out the best way to pause an active, repeating schedule without disrupting future schedules. Here's the scenario: I have a repeating schedule set from 10:00 AM to 8:00 PM daily. If I need to pause the schedule temporarily, my current approach involves stopping monitoring, clearing all restrictions, and then setting a new schedule for the remaining time after the pause. However, this method cancels the repeating schedule entirely, which causes issues when the schedule is supposed to restart the next day at 10:00 AM. Instead, it starts after the pause time, which isn’t what I want. Challenges I'm Facing: Maintaining Repeating Schedules: How can I pause the schedule in a way that ensures it resumes correctly the next day at the intended time (10:00 AM)? DeviceActivityMonitor Logic: Is there a way to deactivate and reactivate the schedule through the DeviceActivityMonitor without fully stopping the monitoring? Ideally, I'd like to retain the original schedule, pause it, and then resume it seamlessly after the pause. What I’ve Tried So Far: I’ve attempted to store the necessary data in the App Groups shared container as a local file. In the DeviceActivityMonitor, I used the schedule's name to identify and retrieve the saved object, planning to use this data to reapply the shielding after the pause. Unfortunately, this approach exceeds the 6MB memory limit of the extension, which is another roadblock. Given these issues, I’m unsure how to move forward. Are there any best practices or alternative approaches that could help manage this situation more effectively? Any insights or suggestions would be greatly appreciated! Thanks in advance for your help.
1
0
476
Aug ’24
Stack feature not working as per plan.
Good Morning/Afternoon/Evening. I'm trying to build a code with a background bar (grey) and above it, we have a ProgressiveBar that starts full and empties as time passes. To be able to stack the elements one above the other I'm trying to use the Zstack function, as shown on the code below, but when simulating the code the progressiveBar is always, on the iPhone screen, showing on top of the background bar, and not above as desired. Could you please review the code below and let me know what I'm missing? `var body: some View { ZStack(alignment: .leading) { // Background bar RoundedRectangle(cornerRadius: 10) .fill(Color.gray.opacity(0.3)) .frame(height: barHeight) // Set height to the specified barHeight // Progress bar GeometryReader { geometry in RoundedRectangle(cornerRadius: 10) .fill(barColor) .frame(width: CGFloat(progress) * geometry.size.width, height: barHeight) .animation(.linear(duration: 1), value: progress) } .cornerRadius(10) // Icon and label HStack { Image(systemName: icon) .foregroundColor(.black) .font(.system(size: 28)) // Increased size .padding(.leading, 8) Spacer() Text(timeString(from: duration * Double(progress))) .foregroundColor(.black) .bold() .font(.system(size: 24)) // Increased size .padding(.trailing, 8) } .frame(width: UIScreen.main.bounds.width * 0.9, height: barHeight) .zIndex(1) // Ensure the HStack is on top } .padding(.horizontal)
3
0
275
Aug ’24