Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.

All subtopics

Post

Replies

Boosts

Views

Activity

@Environment(\.dismiss) causes endless loop in iOS 18.2.1
Hello, I've been using the @Environment(\.dismiss) var dismiss in a SwiftUI app for the last 2 years which means it was working as expected in iOS 16, iOS 17 and for the most part iOS 18 up until iOS 18.2.1 in which it is causing an endless loop and eventually a crash. It seems to be something about using a the @Environment(\.dismiss) with a NavigationLink which seems to cause this issue. When I add a log in my swiftUI views with let _ = Self._printChanges(), I see the following printed out in a loop: CurrentProjectView: _dismiss changed. SurveyView: @self changed. Similar issues have been reported: https://forums.developer.apple.com/forums/thread/720803 https://forums.developer.apple.com/forums/thread/739512 Any idea how to resolve this ?
1
0
217
3w
How to remove margins around built-in views?
I want to have my own background and foreground colors for some views and I am having a bit of trouble. I cannot figure out how to remove the margins around some built-in views. One example is below. The ScrollView portion is always black or white, depending on whether I am I dark mode or not. I've added various colors and borders to see what is going on below. I've also tried adding the modifiers to the Scroll View rather than the TextEditor and it doesn't work at all. If I don't have the .frame modifier on the ScrollView, the TextEditor moves to the top of its frame for some reason. I've played with .contentMargins, .edgeInsets, etc. with no luck How do I get the TextEditor to fill the entire ScrollView without the margin? Thanks! import SwiftUI struct TextEditorView: View { @Binding var editString: String var numberOfLines: Int var lineHeight: CGFloat { UIFont.preferredFont(forTextStyle: .body).lineHeight } var viewHeight: CGFloat { lineHeight * CGFloat(numberOfLines) + 8 } var body: some View { ScrollView([.vertical], showsIndicators: true) { TextEditor(text: $editString) .border(Color.red, width: 5) .foregroundStyle(.yellow) .background(.blue) .frame(minHeight:viewHeight, maxHeight: viewHeight) .scrollContentBackground(.hidden) } .frame(minHeight:viewHeight, maxHeight: viewHeight) } }
0
0
108
3w
Monitoring of the paste(GUI based) operation
I am working on the EndPoint DLP solution project. So I want to monitor the paste operation peformed by the user. So when he uses the keyboard keys then I can monitor them using the event callback. But if user uses the GUI for pasting the data then how can I monitor that ?
0
0
146
3w
Customizing Swipe to Delete Button
Hi, Im trying to customize the button that appear when swiping a for each list for deleting trying to show a red circle and a white trash icon inside it, but instead I get a white empty button ? .swipeActions(edge: .trailing) { Button { deletePatient(patient: patient) } label: { ZStack { Circle() .fill(Color.red) .frame(width: 50, height: 50) Image(systemName: "trash") .foregroundColor(.white) } } .tint(.white) }
3
0
189
3w
Why timer isn't working with button in SwiftUI
.onReceive construction isn't working with button long press gesture but tap is working, it increases count by 1. Construction should increase count every 0.5 seconds if button pressed struct Test: View { @State private var count = 0 @State private var isLongPressed = false var body: some View { VStack { Text("Count: \(count)") Button("Increase") { count += 1 print("Button tapped") } .onLongPressGesture { isLongPressed = true print("Long press started") } .onLongPressGesture(minimumDuration: 0) { isLongPressed = false print("Long press ended") } } .onReceive(Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()) { _ in if isLongPressed { count += 1 print("Count increased: \(count)") } } } }
1
0
161
3w
Window color Changed After Exiting Immersive Mode
Create an Empty visionOS App like this. starts in windowed mode, when I enter immersive mode and then exit back to windowed mode, I notice that the window appears dimmer. I start a simple project with settings as image shown below, and took screenShots of my window before and after entering immersive space then quit, compare them, the color value did become dimmer. The issue is reliably repeatable in a given room. If this issue is experienced, adjusting the display brightness to the maximum value and then back to the initial setting will restore the colors to the correct state. Force to exit the app then reopen it can do the same restoration.https://drive.google.com/file/d/1m-a4ghNlSkHhAQuvOCF_IAfcdYeJA14j/view?usp=sharing
1
0
185
3w
https://developer.apple.com/documentation/swiftui/tab/init(value:content:label:)
As per the documentation link, the Tab initializer in SwiftUI should allow supplying a custom view to the Label. However, the colors used within the Label view are not being honored as expected. I attempted to set custom colors in the Label, but they either default to system-defined styles or are ignored entirely. This behavior does not align with my understanding of how custom views should work in SwiftUI's Label. Am I missing a step or configuration here, or is this a bug in the current implementation? struct ContentView: View { @State private var activeTab: TabItem = .homeTab var body: some View { TabView(selection: $activeTab) { ForEach(TabItem.allCases) { tabItem in Tab(value: tabItem) { getView(for: tabItem) } label: { VStack(spacing: 0) { MainTabButtonView( selected: activeTab == tabItem, tabItem: tabItem ) Text(tabItem.title) } } } } } } private extension ContentView { @ViewBuilder func getView(for tabItem: TabItem) -> some View { switch tabItem { case .homeTab: Text("Home") case .searchTab: Text("Search") case .profileTab: Text("Profile") case .moreTab: Text("More") } } } #Preview { ContentView() } enum TabItem: String, Identifiable, Hashable, CaseIterable { case homeTab case searchTab case profileTab case moreTab var tabImage: String { switch self { case .homeTab: "house" case .searchTab: "magnifying-glass" case .profileTab: "biographic" case .moreTab: "hamburger-menu" } } var title: String { switch self { case .homeTab: "Home" case .searchTab: "Search" case .profileTab: "Profile" case .moreTab: "More" } } var id: String { rawValue } } struct MainTabButtonView: View { private let selected: Bool private let tabItem: TabItem init( selected: Bool, tabItem: TabItem ) { self.selected = selected self.tabItem = tabItem } var body: some View { Image(tabItem.tabImage) .renderingMode(.template) .resizable() .aspectRatio(contentMode: .fill) .frame(width: 30, height: 30) .foregroundStyle( selected ? Color.green : Color.orange ) } } Expected Behavior: The custom colors applied within the Label should render as defined. Actual Behavior: The colors are overridden or ignored, defaulting to the system-defined styles. Environment: Xcode Version: Xcode 16.2 iOS: 18.2 Swift Version: Swift 6
2
0
223
3w
TextField using numberPad shows incorrectly shows autofill for one time code
If I show a textfield in my app and set nothing else on it but the following, The keyboard will show an autofill suggestion from a password manager for a one time code. textField.keyboardType = .numberPad In this case, the text field is for typing in a count, so iOS suggesting to autofill a one time code is incorrect. Setting textField.textContentType to nil has no affect on the behaviour. Prerequisites to reproduce an app with an associated domain an entry in a password manager with a one time code for the domain a textfield with keyboardType set to numberPad
2
0
267
3w
INUIHostedViewControlling ViewController's Life Cycle Events not being Called
I am implementing a new Intents UI Extension and am noticing that the viewWillDisappear, viewDidDisappear, and deinit methods are not being called on my UIViewController that implements INUIHostedViewControlling, when pressing the "Done" button and dismissing the UIViewController. This causes the memory for the UI Extension to slowly increase each time I re-run the UI Extension until it reaches the 120MB limit and crashes. Any ideas as to what's going on here and how to solve this issue? Worth noting that while the memory does continuously increase on iOS versions before iOS 17, only in 17 and later does the 120MB memory limit kick in and crash the extension.
2
0
239
3w
ObservableObject With Closure With Typed Throws Crashes on iOS 17
Having a property inside of an ObservableObject with a type of a closure with a typed throws will crash the app on the initialization of the observable object on iOS 17. Here is an example: struct ContentView: View { @StateObject var myDataSource = MyDataSource() var body: some View { EmptyView() } } enum MyError: Error { case error } class MyDataSource: ObservableObject { let signUp: (Int) throws(MyError) -> Void = { _ in } } If you run this code on iOS 17, the app will crash. The Radar for this issue is FB16399987.
1
0
193
3w
Do not have permission to open the file
In macOS, I am encountering an issue where the system API fails to grant permission to open a file despite enabling the necessary Read/Write permissions within the SandBox. Could you please elucidate the reasons behind this behavior? Thanks! func finderOpenFileSystem(at path: String) { let fileURL = URL(fileURLWithPath: path) guard FileManager.default.fileExists(atPath: path) else { print("Error: File does not exist at path: \(path)") return } let success = NSWorkspace.shared.open(fileURL) if success { print("File opened successfully: \(fileURL)") } else { print("Error: Failed to open file: \(fileURL)") } }
1
0
190
3w
SwiftUI PKCanvasView bounds
I am creating a Bible app with SwiftUI using Text in the background and a PKCanvasView in the front to mark the text and take notes. The user can modify the font and its size and you can navigate to different books and chapters. Each chapter's text has a different size causing the PKCanvasView to have varying sizes. The width of the canvas is always the same but the height changes based on these parameters I just mentioned. If the chapter is long and the height of the canvas exceeds 4000 or some settings cause the text to make the views bound to go beyond 4000, the drawing will enlarge or appear to be occurring in a different location than my pencil. As soon as I lift my pencil, the drawing snaps to the place it belongs. var body: some View { HStack(spacing: 0) { // Main content container ScrollView { ZStack { // Text content VStack { if let chapter = viewModel.currentChapterText { HStack { Text(AttributedString(chapter.html(fontName: fontName, fontSize: fontSize, showVerses: showVerse, showFootnotes: showFootnotes))) .padding() .frame(width: textWidth, alignment: .leading) Color.clear } .frame(width: canvasWidth) } else { Text("Select a book to begin reading") .foregroundColor(.gray) } } // Drawing canvas overlay if showingDrawingTools { DrawingCanvasView( canvasView: $canvasView, toolPicker: toolPicker, frame: CGSize(width: deviceWidth, height: deviceHeight), onSave: saveDrawing ) } } } } .onChange(of: viewModel.currentChapter) { oldValue, newValue in print("BibleContentView - chapter text changed") } }
2
0
154
3w
CATransaction commit() crashed on background thread [EXC_BREAKPOINT: com.apple.root.****-qos.cooperative]
Problem Description We are developing a app for iOS and iPadOS that involves extensive custom drawing of paths, shapes, texts, etc. To improve drawing and rendering speed, we use CARenderer to generate cached images (CGImage) on a background thread. We adopted this approach based on this StackOverflow post: https://stackoverflow.com/a/75497329/9202699. However, we are experiencing frequent crashes in our production environment that we can hardly reproduce in our development environment. Despite months of debugging and seeking support from DTS and the Apple Feedback platform, we have not been able to fully resolve this issue. Our recent crash reports indicate that the crashes occur when calling CATransaction.commit(). We suspect that CATransaction may not be functioning properly outside the main thread. However, based on feedback from the Apple Feedback platform, we were advised to use CATransaction.begin() and CATransaction.commit() on a background thread. If anyone has any insights, we would greatly appreciate it. Code Sample The line CATransaction.commit() is causing the crash: [EXC_BREAKPOINT: com.apple.root.****-qos.cooperative] private let transactionLock = NSLock() // to ensure one transaction at a time private let device = MTLCreateSystemDefaultDevice()! @inline(never) static func drawOnCGImageWithCARenderer( layerRect: CGRect, itemsToDraw: [ItemsToDraw] ) -> CGImage? { // We have encapsulated everything related to CALayer and its // associated creations and manipulations within CATransaction // as suggested by engineers from Apple Feedback Portal. transactionLock.lock() CATransaction.begin() // Create the root layer. let layer = CALayer() layer.bounds = layerRect layer.masksToBounds = true // Add one sublayer for each item to draw itemsToDraw.forEach { item in // We have thousands or hundred thousands of drawing items to add. // Each drawing item may produce a CALayer, CAShapeLayer or CATextLayer. // This is also why we want to utilise CARenderer to leverage GPU rendering. layer.addSublayer( item.createCALayerOrCATextLayerOrCAShapeLayer() ) } // Create MTLTexture and CARenderer. let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: .rgba8Unorm, width: Int(layer.frame.size.width), height: Int(layer.frame.size.height), mipmapped: false ) textureDescriptor.usage = [MTLTextureUsage.shaderRead, .shaderWrite, .renderTarget] let texture = device.makeTexture(descriptor: textureDescriptor)! let renderer = CARenderer(mtlTexture: texture) renderer.bounds = layer.frame renderer.layer = layer.self /* ********************************************************* */ // From our crash report, this is where the crash happens. CATransaction.commit() /* ********************************************************* */ transactionLock.unlock() // Rendering layers onto MTLTexture using CARenderer. renderer.beginFrame(atTime: 0, timeStamp: nil) renderer.render() renderer.endFrame() // Draw MTLTexture onto image. guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let ciImage = CIImage(mtlTexture: texture, options: [.colorSpace: colorSpace]) else { return nil } // Convert CIImage to CGImage. let context = CIContext() return context.createCGImage(ciImage, from: ciImage.extent) }
0
1
209
3w
How to share 'back facing' iOS camera app at same time Eye Tracking app needs 'front facing' camera?
While using my xmas present of a new iPhone and iOS 18.2, I figured I'd try the Eye Tracker app. I've been working with clients successfully using Tobii and other existing eye trackers. In my limited tests, Apple has room for improvement. My main issue is with the camera app which cannot be used at the same time while using the Eye Tracker app. I get an error popup from Apple: Camera is use by another app The image below is from my app showing the popup message "Camera in use by another app", but the same error occurs on the installed camera app. This error is from Apple, not my app. For terminology: 'front' camera is the one pointing at the user (the selfi camera) while 'back' camera is the main one with multiple lenses. Eye tracking needs the 'front' camera. It seems when an app uses the camera, it takes over both the front and back facing cameras (since you might swap them). Thus another app, especially Eye Tracking, cannot use just the front facing camera at the same time. That limits use of Eye Tracking, in particular one cannot take pictures or click any buttons on an app that uses the camera. Anyone know of a way for an app to not take over both front and back cameras at the same time? If I can separate them, the Eye Tracker could use the front camera while the camera uses the back camera.
1
0
178
3w
Problem with connecting the workout data to a SwiftUI View.
Hello. I am building an app that shows my walk workouts and in the detail view I want to show the route I took while walking, similar to that of the Apple Fitness App. There is a problem though, I cannot seem to understand how to connect the @State property workoutLocations array that would be used to draw the route on the map with what I get from the query. The task does successfully fetches the data but then when I try to use it later in a do-catch block nothing happens. What am I missing here? import SwiftUI import MapKit import HealthKit struct DetailView: View { @Environment(HealthKitManager.self) var healthKitManager let workout: HKWorkout @State private var workoutLocations: [CLLocation] = [] var body: some View { ScrollView { //... } .task { guard let store = self.healthKitManager.healthStore else { fatalError("healthStore is nil. App is in invalid state.") } let walkingObjectQuery = HKQuery.predicateForObjects(from: workout) let routeQuery = HKAnchoredObjectQueryDescriptor(predicates: [.workoutRoute(walkingObjectQuery)], anchor: nil) let queryResults = routeQuery.results(for: store) let task = Task { var workoutRouteLocations: [CLLocation] = [] for try await result in queryResults { let routeSamples = result.addedSamples for routeSample in routeSamples { let routeQueryDescriptor = HKWorkoutRouteQueryDescriptor(routeSample) let locations = routeQueryDescriptor.results(for: store) for try await location in locations { workoutRouteLocations.append(location) print(workoutRouteLocations.count) // this prints out the number of locations in the sample. } } } return workoutRouteLocations } do { print(try await task.value.count) // this prints nothing. Therefore if I try to update workoutLocations array from here it would do nothing as well // workoutLocations = try await task.value therefore does nothing and the array just doesn't get populated with the results of the task } catch { print(error) } } } }
2
0
286
3w
TextKit 2 Background drawing incorrect
Hi I am drawing TextKit2 managed NSAttributedStrings into a NSBitmapImageRep successfully, enumerating the Text Layout Fragments is giving me bogus background drawing This is the core drawing code, its pretty simple: I manage the flipped property myself since NSTextLayoutManager assumes a flipped coordinate. if let context = NSGraphicsContext(bitmapImageRep: self.textImageRep!) { NSGraphicsContext.current = context let rect = NSRect(origin: .zero, size: self.outputSize) NSColor.clear.set() rect.fill() // Flip the context context.cgContext.saveGState() context.cgContext.translateBy(x: 0, y: self.outputSize.height) context.cgContext.scaleBy(x: 1.0, y: -1.0) let textOrigin = CGPoint(x: 0.0, y: 0.0 ) let titleRect = CGRect(origin: textOrigin, size: self.themeTextContainer.size) NSColor.orange.withAlphaComponent(1).set() titleRect.fill() self.layoutManager.enumerateTextLayoutFragments(from: nil, using: { textLayoutFragment in // Get the fragment's rendering bounds let fragmentBounds = textLayoutFragment.layoutFragmentFrame print("fragmentBounds: \(fragmentBounds)") // Render the fragment into the context textLayoutFragment.draw(at: fragmentBounds.origin, in: context.cgContext) return true }) context.cgContext.restoreGState() } NSGraphicsContext.restoreGraphicsState() I have a mutable string which has various paragraph styles which I add to the layout manager / text storage like so let titleParagraphStyle = NSMutableParagraphStyle() titleParagraphStyle.alignment = .center titleParagraphStyle.lineBreakMode = .byWordWrapping titleParagraphStyle.lineBreakStrategy = .standard var range = NSMakeRange(0, self.attributedProgrammingBlockTitle.length) self.attributedProgrammingBlockTitle.addAttribute(.foregroundColor, value: NSColor(red: 243.0/255.0, green: 97.0/255.0, blue: 97.0/255.0, alpha: 1.0), range:range) self.attributedProgrammingBlockTitle.addAttribute(.backgroundColor, value: NSColor.cyan, range:range) self.attributedProgrammingBlockTitle.addAttribute(.font, value: NSFont.systemFont(ofSize: 64), range:range) self.attributedProgrammingBlockTitle.addAttribute(.paragraphStyle, value:titleParagraphStyle, range:range) range = NSMakeRange(0, self.attributedThemeTitle.length) self.attributedThemeTitle.addAttribute(.foregroundColor, value: NSColor.white, range:range ) self.attributedThemeTitle.addAttribute(.backgroundColor, value: NSColor.purple, range:range) self.attributedThemeTitle.addAttribute(.font, value: NSFont.systemFont(ofSize: 48), range:range) self.attributedThemeTitle.addAttribute(.paragraphStyle, value:NSParagraphStyle.default, range:range) range = NSMakeRange(0, self.attributedText.length) self.attributedText.addAttribute(.foregroundColor, value: NSColor.white, range:range ) self.attributedText.addAttribute(.backgroundColor, value: NSColor.yellow, range:range) self.attributedText.addAttribute(.font, value: NSFont.systemFont(ofSize: 36), range:range) self.attributedText.addAttribute(.paragraphStyle, value:NSParagraphStyle.default, range:range) let allText = NSMutableAttributedString() allText.append(self.attributedProgrammingBlockTitle) allText.append(NSAttributedString(string: "\n\r")) allText.append(self.attributedThemeTitle) allText.append(NSAttributedString(string: "\n\r")) allText.append(self.attributedText) self.textStorage.textStorage?.beginEditing() self.textStorage.textStorage?.setAttributedString(allText) self.textStorage.textStorage?.endEditing() self.layoutManager.ensureLayout(for: self.layoutManager.documentRange) however, i get incorrect drawing for the background color font attributes. Its origin is zero, and not correctly aligned at all with the text. How can I get correct rendering of backgrounds from TextKit2? Here is an image of my output:
3
0
356
3w
NSUIActivityDocumentMonitor throws a strange exception
This class is throwing an NSInternalInconsistencyException immediately after my app delegate gets an ApplicationWillResignActive message as shown below. This happens only on 15.2. In the Event processing run loop in my NSApplication subclass, I added a couple of lines to monitor the value of "mainWindow" as defined in NSApplication. It contains a valid window pointer until after the ApplicationWillResignActive message. FYI I do not appear to ever get a ApplicationDidResignActive call. My questions: What is NSUIActivityDocumentMonitor and what exactly does it do? I can find no documentation on it at all. Should I assume it is created by NSDocument? Can or should I prevent its creation? The error text implies that my NSApplication subclass is not sending out a notification when its "mainWindow" property changes (in my case it appears to get changed to nil as a result of resigning the active state). That has never been an issue before now. This does not occur on ANY other prior macOS releases including 15.1. How can I prevent this error that is being thrown by a previously unknown class? Are there new recommended actions I should take when I get the ApplicationWillResignActive call? Wouldn't NSApplication/NSObject handle the KVO compliance issue (notify observers of a change to "mainWindow")? FYI, this only happens when I have an opened document window (either new or opened from the desktop). If I ignore the error in my run loop, the app continues normally in the background and can be brought back to be the front app no problem. I'm at my wits end trying to get rid of this (properly instead of ignoring the error) and could use some guidance. This is a mature app in use by many clients. Objective C.
0
0
126
3w
Calling Async Functions in SwiftUI
Hi, I'd like to call an Async function upon a state change or onAppear() but I'm not sure how to do so. Below is my code: .onAppear() { if !subscribed { await Subscriptions().checkSubscriptionStatus() } } class Subscriptions { var subscribed = UserDefaults.standard.bool(forKey: "subscribed") func checkSubscriptionStatus() async { if !subscribed { await loadProducts() } } func loadProducts() async { for await purchaseIntent in PurchaseIntent.intents { // Complete the purchase workflow. await purchaseProduct(purchaseIntent.product) } } func purchaseProduct(_ product: Product) async { // Complete the purchase workflow. do { try await product.purchase() } catch { // Add your error handling here. } // Add your remaining purchase workflow here. } }
1
0
168
3w