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
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

A Summary of the WWDC25 Group Lab - UI Frameworks
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for UI Frameworks. How would you recommend developers start adopting the new design? Start by focusing on the foundational structural elements of your application, working from the "top down" or "bottom up" based on your application's hierarchy. These structural changes, like edge-to-edge content and updated navigation and controls, often require corresponding code modifications. As a first step, recompile your application with the new SDK to see what updates are automatically applied, especially if you've been using standard controls. Then, carefully analyze where the new design elements can be applied to your UI, paying particular attention to custom controls or UI that could benefit from a refresh. Address the large structural items first then focus on smaller details is recommended. Will we need to migrate our UI code to Swift and SwiftUI to adopt the new design? No, you will not need to migrate your UI code to Swift and SwiftUI to adopt the new design. The UI frameworks fully support the new design, allowing you to migrate your app with as little effort as possible, especially if you've been using standard controls. The goal is to make it easy to adopt the new design, regardless of your current UI framework, to achieve a cohesive look across the operating system. What was the reason for choosing Liquid Glass over frosted glass, as used in visionOS? The choice of Liquid Glass was driven by the desire to bring content to life. The see-through nature of Liquid Glass enhances this effect. The appearance of Liquid Glass adapts based on its size; larger glass elements look more frosted, which aligns with the design of visionOS, where everything feels larger and benefits from the frosted look. What are best practices for apps that use customized navigation bars? The new design emphasizes behavior and transitions as much as static appearance. Consider whether you truly need a custom navigation bar, or if the system-provided controls can meet your needs. Explore new APIs for subtitles and custom views in navigation bars, designed to support common use cases. If you still require a custom solution, ensure you're respecting safe areas using APIs like SwiftUI's safeAreaInset. When working with Liquid Glass, group related buttons in shared containers to maintain design consistency. Finally, mark glass containers as interactive. For branding, instead of coloring the navigation bar directly, consider incorporating branding colors into the content area behind the Liquid Glass controls. This creates a dynamic effect where the color is visible through the glass and moves with the content as the user scrolls. I want to know why new UI Framework APIs aren’t backward compatible, specifically in SwiftUI? It leads to code with lots of if-else statements. Existing APIs have been updated to work with the new design where possible, ensuring that apps using those APIs will adopt the new design and function on both older and newer operating systems. However, new APIs often depend on deep integration across the framework and graphics stack, making backward compatibility impractical. When using these new APIs, it's important to consider how they fit within the context of the latest OS. The use of if-else statements allows you to maintain compatibility with older systems while taking full advantage of the new APIs and design features on newer systems. If you are using new APIs, it likely means you are implementing something very specific to the new design language. Using conditional code allows you to intentionally create different code paths for the new design versus older operating systems. Prefer to use if #available where appropriate to intentionally adopt new design elements. Are there any Liquid Glass materials in iOS or macOS that are only available as part of dedicated components? Or are all those materials available through new UIKit and AppKit views? Yes, some variations of the Liquid Glass material are exclusively available through dedicated components like sliders, segmented controls, and tab bars. However, the "regular" and "clear" glass materials should satisfy most application requirements. If you encounter situations where these options are insufficient, please file feedback. If I were to create an app today, how should I design it to make it future proof using Liquid Glass? The best approach to future-proof your app is to utilize standard system controls and design your UI to align with the standard system look and feel. Using the framework-provided declarative API generally leads to easier adoption of future design changes, as you're expressing intent rather than specifying pixel-perfect visuals. Pay close attention to the design sessions offered this year, which cover the design motivation behind the Liquid Glass material and best practices for its use. Is it possible to implement your own sidebar on macOS without NSSplitViewController, but still provide the Liquid Glass appearance? While technically possible to create a custom sidebar that approximates the Liquid Glass appearance without using NSSplitViewController, it is not recommended. The system implementation of the sidebar involves significant unseen complexity, including interlayering with scroll edge effects and fullscreen behaviors. NSSplitViewController provides the necessary level of abstraction for the framework to handle these details correctly. Regarding the SceneDelagate and scene based life-cycle, I would like to confirm that AppDelegate is not going away. Also if the above is a correct understanding, is there any advice as to what should, and should not, be moved to the SceneDelegate? UIApplicationDelegate is not going away and still serves a purpose for application-level interactions with the system and managing scenes at a higher level. Move code related to your app's scene or UI into the UISceneDelegate. Remember that adopting scenes doesn't necessarily mean supporting multiple scenes; an app can be scene-based but still support only one scene. Refer to the tech note Migrating to the UIKit scene-based life cycle and the Make your UIKit app more flexible WWDC25 session for more information.
Topic: UI Frameworks SubTopic: General
0
0
731
Jun ’25
QuickLook Library updated text tampered on PDF
We were using below delegate methods from QuickLook to get modified PDF file URL after the sketching But we are not able see the multi line text properly laid out on PDF and part of text missing. Same time Other pencil kit tools are working as expected. `func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: any QLPreviewItem)` We tested all code in iOS 18.2. Please let us know if the text edited URL on PDF can be retrieved in any possible way without tampering text
0
0
400
Feb ’25
Observe currentEDRHeadroom for changes
Is there a way to observe the currentEDRHeadroom property of UIScreen for changes? KVO is not working for this property... I understand that I can query the current headroom in the draw(...) method to adapt the rendering. However, our apps only render on-demand when the user changes parameters. But we would also like to re-render when the current EDR headroom changes to adapt the tone mapping to the new environment. The only solution we've found so far is to continuously query the screen for changes, which doesn't seem ideal. It would be better if the property would be observable via KVO or if there would be a system notification to listen for. Thanks!
2
0
1.3k
Feb ’25
On macOS SwiftUI.TimelineView() inside NSViewController is causing AutoLayout recalculations
I have a complex app that requires the main SwiftUI view of the app to be embedded inside an NSHostingView which is a subview of an NSViewController's view. Then this NSViewController is wrapped using NSViewControllerRepresentable to be presented using SwiftUI's Window. And if I have a TimelineView inside my SwiftUI view hierarchy, it causes constant recalculation of the layout. Here's a simplified demo code: @main struct DogApp: App { private let dogViewController = DogViewController() var body: some Scene { Window("Dog", id: "main") { DogViewControllerUI() } } } private struct DogViewControllerUI: NSViewControllerRepresentable { let dogViewController = DogViewController () func makeNSViewController(context: Context) -> NSViewController { dogViewController } func updateNSViewController(_ nsViewController: NSViewController, context: Context) {} func sizeThatFits(_ proposal: ProposedViewSize, nsViewController: NSViewController, context: Context) -> CGSize? { debugPrint("sizeThatFits", proposal) return nil } } public class DogViewController: NSViewController { public override func viewDidLoad() { super.viewDidLoad() let mainView = MainView() let hostingView = NSHostingView(rootView: mainView) view.addSubview(hostingView) hostingView.translatesAutoresizingMaskIntoConstraints = false hostingView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true hostingView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true hostingView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true hostingView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } } struct MainView: View { var body: some View { VStack { TimelineView(.animation) { _ in Color.random .frame(width: 100, height: 100) } } } } extension Color { static var random: Color { Color( red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1) ) } } When running it's printing out this repeatedly (multiple times a second). "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(559.0), height: Optional(528.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(0.0), height: Optional(0.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(559.0), height: Optional(528.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(0.0), height: Optional(0.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(559.0), height: Optional(528.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(0.0), height: Optional(0.0)) "sizeThatFits" SwiftUI.ProposedViewSize(width: Optional(559.0), height: Optional(528.0)) If I run an equivalent code for an iPad, it only prints twice. If I comment out TimelineView on macOS, then it only prints out the above logs when resizing the app window. The main reason this is an issue is that it's clearly causing dramatic degradation in performance. I was told to submit a bug report after I submitted TSI so a SwiftUI engineer could investigate it. Case-ID: 7461887. FB13810482. This was back in May but I received no response. LLMs are no help, and I've experimented with all sorts of workarounds. My last hope is this forum, maybe someone has an idea of what might be going on and why the recalculation is happening constantly on macOS.
1
0
388
Feb ’25
Is using to SwiftUI entry point and using NSViewControllerRepresentable to add NSViewController to hirarchy right approach ?
In macOS application, we are using SwiftUI as an entry point to our application and attaching appdelegate using NSApplicationDelegateAdaptor. We are using NSViewControllerRepresentable to add a View Controller to the hiracrchy so that we can store intance of viewcontroller and add content to it programatically . @main struct TWMainApp: App { @NSApplicationDelegateAdaptor private var appDelegate: TWAppDelegate internal var body : some Scene { TWInitialScene () } } TWInitialScene : public struct TWInitialScene : Scene { public var body : some Scene { WindowGroup { TWInitialView () } } } TWInitialView : struct TWInitialView : View { @Environment(\.scenePhase) private var scenePhase var body : some View { TWAppKitToSwiftUIBridge () } } TWAppKitToSwiftUIBridge : struct TWNSKitToSwiftUIBridge : NSViewControllerRepresentable { func makeNSViewController(context: Context) -> TWNSViewController { let view_hierarchy : TWNSViewController view_hierarchy = TWStaticContext.sViewController return view_hierarchy } func updateNSViewController(_ nsViewController: TWNSViewController, context: Context) { } } @objc public class TWStaticContext : NSObject { public static let sViewController = TWNSViewController () public override init () {} @objc public static func GetViewController () -> TWNSViewController { return TWStaticContext.sViewController } } public class TWNSViewController : NSViewController { override public func viewDidLoad () { super.viewDidLoad () } } To add content to the hirarchy we are accessing viewcontroller's intance and adding content to it like this : public func PaintInitialScreen () { let label = NSTextField(labelWithString: "TW window") label.frame = NSRect(x: 100, y: 200, width: 200, height: 200) // Adding content to viewcontroller TWStaticContext.sViewController.view.addSubview(label) } We are using this approach because we have a contraint in our application that we have to update UI programatically and on compile time we dont know what we want to show . We will be adding content on runtime based on how many button we want, what label we want , where to place it etc. When we were using purely appKit application, doing things programatically was simple but since SwiftUI is a declarative application we have to use above approach. Rational for shifting to SwiftUI entry point is that we want our application to be future safe and since apple is more inclined to SwiffUI, we want to design our entry flow to use SwiftUI entry point . And SwiftUI being declarative, we are using appKit to add content to hiracrchy programtically. We have used similar apprach in iOS also , where are using UIApplicationDelegateAdaptor inplace of NSApplicationAdaptor . And UIViewControllerReprestable in place of NSViewControllerRepresentable. Is this right approach to use ?
1
0
495
Feb ’25
Signal SIGABRT on accessing values from SwiftData query
I work on an iOS app using SwiftUI and SwiftData. I added a computed property to one of my models - Parent - that uses relationship - array of Child models - data and I started getting strange problems. Let me start with models: @Model final class Parent { var name: String @Relationship(deleteRule: .cascade, inverse: \Child.parent) var children: [Child]? = [] var streak: Int { // Yes, I know that's not optimal solution for such counter ;) guard let children = children?.sorted(using: SortDescriptor(\.date, order: .reverse)) else { return 0 } var date = Date.now let calendar = Calendar.current for (index, child) in children.enumerated() { if !calendar.isDate(child.date, inSameDayAs: date) { return index } date = calendar.date(byAdding: .day, value: -1, to: date) ?? .now } return children.count } init(name: String) { self.name = name } } @Model final class Child { var date: Date @Relationship(deleteRule: .nullify) var parent: Parent? init(date: Date, parent: Parent) { self.date = date self.parent = parent } } At first everything works as expected. The problem arises once I try to remove one of child from the parent instance. I remove the value from context and save changes without any problems, at least not ones that can be caught by do { } catch. But instead of refreshing UI I get an signal SIGABRT somewhere inside SwiftData internals that points to the line where I'm trying (inside View body) get a child from a Query: struct LastSevenDaysButtons: View { @Environment(\.modelContext) private var modelContext @Query private var children: [Child] private let dates: [Date] private let parent: Parent init(for parent: Parent) { self.parent = parent var lastSevenDays = [Date]() let calendar = Calendar.current let firstDate = calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: .now)) ?? .now var date = firstDate while date <= .now { lastSevenDays.append(date) date = calendar.date(byAdding: .day, value: 1, to: date) ?? .now } dates = lastSevenDays let parentId = parent.persistentModelID _children = Query( filter: #Predicate { $0.parent?.persistentModelID == parentId && $0.date >= firstDate }, sort: [SortDescriptor(\Child.date, order: .reverse)], animation: .default ) } var body: some View { VStack { HStack(alignment: .top) { ForEach(dates, id: \.self) { date in // Here is the last point on stack from my code that I see let child = children.first { $0.date == date } Button { if let child { modelContext.delete(child) } else { modelContext.insert(Child(date: date, parent: parent)) } do { try modelContext.save() } catch { print("Can't save changes for \(parent.name) on \(date.formatted(date: .abbreviated, time: .omitted)): \(error.localizedDescription)") } } label: { Text("\(date.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(child == nil ? .red : .blue) } } } } } } The LastSevenDaysButtons View is kind of deep in a View hierarchy: RootView -> ParentList -> ParentListItem -> LastSevenDaysButtons However once I move insides of ParentList to RootView application works just fine, although I see and warning: === AttributeGraph: cycle detected through attribute 6912 ===. What could be that I do wrong in here? I believe it must something I'm missing here, but after 2 days of debug, trial and errors, I can't think clearly anymore. Here is the minimal repro I managed to create: Signal SIGABRT on accessing values from SwiftData query
3
0
750
Feb ’25
Difficulty Localizing App Display Name Based on Region in iOS.
I have an application named "XY" that has been launched in several countries. Now, I intend to launch it in Turkey, but we are facing legal issues preventing us from using "XY" as the app's display name. Following the documentation, I localized the app's display name to "ZX" for both Turkish and English (Turkey). However, when users change their device settings, they do not see an option for English (Turkey) language selection. I assumed that for Turkish users, English (Turkey) would be the default language, but this is not the case. Could someone please assist me in resolving this issue? I've investigated options for localizing the display name based on region, but it seems that this functionality isn't feasible on iOS. In contrast, it's relatively straightforward to achieve on Android platforms.
0
0
450
Mar ’25
Performing simulations in the UI elements in uikit
I wanted to perform simulation in my application as a self tour guide for my user. For this I want to programatically simulate various user interaction events like button click, keypress event in the UITextField or moving the cursor around in the textField. These are only few examples to state, it can be any user interaction event or other events. I wanted to know what is the apple recommendation on how should these simulations be performed? Is there something that apple offers like creating an event which can be directly executed for simulations. Is there some library available for this purpose?
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
316
Feb ’25
SwiftUI SimultaneousGesture with RotateGesture and MagnifyGesture fails if only one gesture is recognized
I'm trying to combine a RotateGesture and a MagnifyGesture within a single SwiftUI view using SimultaneousGesture. My goal is to allow users to rotate and zoom an image (potentially at the same time). However, I’m running into a problem: If only one gesture (say, the magnification) starts and finishes without triggering the other (rotation), it seems that the rotation gesture is considered "failed." After that, no further .onChanged or .onEnded callbacks fire for either gesture until the user lifts their fingers and starts over. Here’s a simplified version of my code: struct ImageDragView: View { @State private var scale: CGFloat = 1.0 @State private var lastScale: CGFloat = 1.0 @State private var angle: Angle = .zero @State private var lastAngle: Angle = .zero var body: some View { Image("Stickers3") .resizable() .aspectRatio(contentMode: .fit) .frame(height: 100) .rotationEffect(angle, anchor: .center) .scaleEffect(scale) .gesture(combinedGesture) } var combinedGesture: some Gesture { SimultaneousGesture( RotateGesture(minimumAngleDelta: .degrees(8)), MagnifyGesture() ) .onChanged { combinedValue in if let magnification = combinedValue.second?.magnification { let minScale = 0.2 let maxScale = 5.0 let newScale = magnification * lastScale scale = max(min(newScale, maxScale), minScale) } if let rotation = combinedValue.first?.rotation { angle = rotation + lastAngle } } .onEnded { _ in lastScale = scale lastAngle = angle } } } If I pinch and rotate together (or just rotate), both gestures work as expected. But if I only pinch (or, sometimes, if the rotation amount doesn’t meet minimumAngleDelta), subsequent gestures don’t trigger the .onChanged or .onEnded callbacks anymore, as if the entire gesture sequence is canceled. I found that setting minimumAngleDelta: .degrees(0) helps because then rotation almost never fails. But I’d like to understand why this happens and whether there’s a recommended way to handle the situation where one gesture might be recognized but not the other, without losing the gesture recognition session entirely. Is there a known workaround or best practice for combining a pinch and rotate gesture where either one might occur independently, but we still want both gestures to remain active? Any insights would be much appreciated!
1
0
271
Mar ’25
Adding Markdown support in notes app
Hi guys, I’m making a simple note taking app and I want to support markdown functionality. I have tried to find libraries and many other GitHub repos but some of them are slow and some of them are very hard to implement and not very customizable. In WWDC 22 apple also made a markdown to html document app and I also looked at that code and it was awesome. It was fast and reliable (Apple btw). But the only problem I am facing is that the markdown text is on the left side and the output format is on the right in the form of html. I don’t want that I want both in the same line. In bear notes and things 3 you can write in markdown and you can see that it is converting in the same line. I have also attached example videos. So, I have markdown parser by apple but the only thing in the way is that it is converting it into a html document. Please help me with this. Also please look into the things 3 video they have also completely customized the text attributes selection menu. By default with UITextView we can only enable text attributes and it shows like this. By clicking more we get the complete formatting menu but not the slider menu which is more convenient. Please also help me this. I don’t know if I can provide apple file but it is from wwdc 22 supporting desktop class interaction
0
0
382
Feb ’25
tvOS: Search Keyboard Unresponsive After Dismissing Custom Controller with Embedded TVDigitEntryViewController
Description I'm developing a tvOS application where I utilize a UISearchController embedded within a UISearchContainerViewController for search functionality. In a particular flow, a custom view controller contains a TVDigitEntryViewController as a child, with its modalPresentationStyle set to .blurOverFullScreen. The issue arises when a user initiates the PIN entry but decides to cancel and return to the search interface without entering a PIN. Upon returning, the search keyboard is no longer visible, and attempts to focus or interact with it are unsuccessful. Steps to Reproduce Initialize and present a UISearchContainerViewController that contains a UISearchController with a results view controller. Within the search results, present a custom view controller containing TVDigitEntryViewController as a child, setting its modalPresentationStyle to .blurOverFullScreen. Dismiss the custom view controller without entering a PIN (e.g., by pressing the Menu button on the remote). Observe that upon returning to the search interface, the keyboard is missing, and focus interactions are unresponsive. Observed Behavior After dismissing the custom view controller with TVDigitEntryViewController, the search keyboard does not reappear, and the focus system seems to lose track of the search input field. Expected Behavior The search keyboard should remain visible and functional after dismissing the custom view controller, allowing users to continue their search without interruption. Additional Context I have reviewed the TVDigitEntryViewController documentation (developer.apple.com) and related discussions on the Apple Developer Forums but have not found a solution to this specific issue. Questions Has anyone encountered a similar issue or have insights into why the search keyboard becomes unresponsive after dismissing a .blurOverFullScreen modal with a child TVDigitEntryViewController? Are there recommended practices to ensure the search keyboard remains active and focusable after such modal presentations? Any guidance or suggestions would be greatly appreciated. Thank you!
3
0
457
Feb ’25
Task cancellation behaviour
Hi everyone, I believe this should be a simple and expected default behavior in a real-world app, but I’m unable to make it work: 1. I have a View (a screen/page in this case) that calls an endpoint using async/await. 2. If the endpoint hasn’t finished, but I navigate forward to a DetailView, I want the endpoint to continue fetching data (i.e., inside the @StateObject ViewModel that the View owns). This way, when I go back, the View will have refreshed with the fetched data once it completes. 3. If the endpoint hasn’t finished and I navigate back to the previous screen, I want it to be canceled, and the @StateObject ViewModel should be deinitialized. I can achieve 1 and 3 using the .task modifier, since it automatically cancels the asynchronous task when the view disappears: view .task { await vm.getData() } I can achieve 1 and 2 using a structured Task in the View (or in the ViewModel, its the same behavior), for example: .onFirstAppearOnly { Task { away vm.getData() } } onFirstAppearOnly is a custom modifier that I have for calling onAppear only once in view lifecycle. Just to clarify, dont think that part is important for the purpose of the example But the question is: How can I achieve all three behaviors? Is this really such an unusual requirement? My minimum deployment target is iOS 15, and I’m using NavigationView + NavigationLink. However, I have also tried using NavigationStack + NavigationPath and still couldn’t get it to work. Any help would be much appreciated. Thank you, folks!
0
0
418
Feb ’25
Modifying the native selection menu ios
I am working on a React Native application where I want to modify the native text selection menu (the menu that appears when you long-press on text). Specifically, I want to add a custom option alongside the default ones like Copy, Look Up, Translate, Search Web, and Share. Is there a way to modify the native text selection menu inside a WebView on iOS? How can I add a custom menu option to the default text selection menu while keeping all the default options intact?
1
0
441
Feb ’25
Memory Leak in WatchOS 11.2 with NavigationTitle in Presented Sheet
I would like to report a memory leak issue in watchOS 11.2 that occurs when using .navigationTitle() inside a sheet. This behavior is reproducible both on the simulator and on a real device, but not on iOS. While this does not register as a leak in Instruments, the deinit of the DetailsViewModel is never called, and multiple instances of the view model accumulate in the Memory Graph Debugger. Commenting out .navigationTitle("Sheet View") resolves the issue, and deinit prints as expected. Using @MainActor on the DetailsViewModel does not fix the issue. Nor does switching to @StateObject and using ObservableObject resolve the memory retention. This issue seems related to other SwiftUI memory leaks that have been reported: https://developer.apple.com/forums/thread/738840 https://developer.apple.com/forums/thread/736110?login=true&page=1#769898022 https://developer.apple.com/forums/thread/737967?answerId=767599022#767599022 Feedback Number: FB16442048 struct MainView: View { var body: some View { NavigationStack { NavigationLink("Details", value: 1) .navigationDestination(for: Int.self) { _ in DetailsView() } } } } struct SheetObject: Identifiable { let id = UUID() let date: Date let value: Int } @Observable @MainActor final class DetailsViewModel { var sheetObject: SheetObject? init() { print("Init") } deinit { print("Deinit") } func onAppear() async { try? await Task.sleep(for: .seconds(2)) sheetObject = .init(date: .now, value: 1) } } struct DetailsView: View { @State private var viewModel = DetailsViewModel() @Environment(\.dismiss) var dismiss var body: some View { Text("Detail View. Going to sheet, please wait...") .task { await viewModel.onAppear() } .sheet(item: $viewModel.sheetObject) { sheetObject in SheetView(sheetObject: sheetObject) .onDisappear { dismiss() } } } } struct SheetView: View { let sheetObject: SheetObject @Environment(\.dismiss) var dismiss var body: some View { NavigationStack { VStack { Text(sheetObject.date.formatted()) Text(sheetObject.value.formatted()) Button("Dismiss") { dismiss() } } .navigationTitle("Sheet View") // This line causes a memory leak. Commenting out, you will see "Deinit" be printed. } } }
Topic: UI Frameworks SubTopic: SwiftUI
2
0
279
Feb ’25
SwiftUI Tabview - how to "kill" the views we do not use
I have the MainView as the active view if the user is logged in(authenticated). the memory allocations when we run profile is pretty good. We have graphql fetching, we have token handling eg: This is All heap: 1 All Heap & Anonymous VM 13,90 MiB 65408 308557 99,10 MiB 373965 Ratio: %0.14, %0.86 After what i have checked this is pretty good for initialise and using multiple repositories eg. But when we change tabs: 1 All Heap & Anonymous VM 24,60 MiB 124651 543832 156,17 MiB 668483 Ratio: %0.07, %0.40 And that is not pretty good. So i guess we need to "kill" it or something. How? I have tried some techniques in a forum this was a recommended way: public struct LazyView<Content: View>: View { private let build: () -> Content @State private var isVisible = false public init(_ build: @escaping () -> Content) { self.build = build } public var body: some View { build() Group { if isVisible { build() } else { Color.clear } } .onAppear { isVisible = true } .onDisappear { isVisible = false } } } But this did not help at all. So under here is the one i use now. So pleace guide me for making this work. import DIKit import CoreKit import PresentationKit import DomainKit public struct MainView: View { @Injected((any MainViewModelProtocol).self) private var viewModel private var selectedTabBinding: Binding<MainTab> { Binding( get: { viewModel.selectedTab }, set: { viewModel.selectTab($0) } ) } public init() { // No additional setup needed } public var body: some View { NavigationStack(path: Binding( get: { viewModel.navigationPath }, set: { _ in } )) { TabView(selection: selectedTabBinding) { LazyView { FeedTabView() } .tabItem { Label("Feed", systemImage: "house") } .tag(MainTab.feed) LazyView { ChatTabView() } .tabItem { Label("Chat", systemImage: "message") } .tag(MainTab.chat) LazyView { JobsTabView() } .tabItem { Label("Jobs", systemImage: "briefcase") } .tag(MainTab.jobs) LazyView { ProfileTabView() } .tabItem { Label("Profile", systemImage: "person") } .tag(MainTab.profile) } .accentColor(.primary) .navigationDestination(for: MainNavigationDestination.self) { destination in switch destination { case .profile(let userId): Text("Profile for \(userId)") case .settings: Text("Settings") case .jobDetails(let id): Text("Job details for \(id)") case .chatThread(let id): Text("Chat thread \(id)") } } } } } import SwiftUI public struct LazyView<Content: View>: View { private let build: () -> Content public init(_ build: @escaping () -> Content) { self.build = build } public var body: some View { build() } }
0
0
207
Mar ’25
Animating Text foregroundStyle with gradients
Hello! We can animate Text color via foregroundStyle very nicely in SwiftUI like so: Text("Some text here") .foregroundStyle(boolValue ? Color.green : Color.blue) withAnimation { boolValue.toggle() } However, if the foregroundStyle is a gradient, the color of the Text view changes immediately without animation. The code below works to animate a gradient foregroundStyle on an SF Symbol, but it does not work when applied to a Text view. Is it possible to animate a Text view foregroundStyle between gradient values? Image(systemName: "pencil.circle.fill") .foregroundStyle(boolValue ? .linearGradient(colors: [.red, .orange], startPoint: .top, endPoint: .bottom) : .linearGradient(colors: [.green, .blue], startPoint: .top, endPoint: .bottom)) Thanks for your help!
1
0
332
Mar ’25
`Text` (Label) text color issue during app resuming from suspended (changes from black to light or vice versa, depending on current appearance mode).
Its important to note that this same app did not have this issue in iOS 17. Ever since iOS 18 I have noticed that when application written in SwiftUI uses Label with the default color (which auto changes between light and dark appearance), from time to time when resuming an application that has been in the background, the color of those labels (only the Label elements) switches from the opposite to the correct one. Here is an example: Steps to reproduce Phone is in dark appearance Open app Labels text color is white and labels background is black Go to home so that app is on background Wait random time (does not happen all the time), some times 1 min some times 10 Reopen the application. During the opening transition the Label text color was changed while the app was in suspended mode to the light appearance variant (black) Once the app opening transition finishes the Label text color switches back to the correct color for dark appearance (white) Same issue happens if you start from light appearance. I cannot reproduce this on Xcode simulators, I have tried to force memory warning to check if that has anything to do with it but that also does not cause the issue to appear on simulators. For now I can only reproduce this on real device. Screenshots Here is screenshots of the above example: During transition After transition
Topic: UI Frameworks SubTopic: SwiftUI
4
0
406
Feb ’25
SwiftUI subview .frame ignored on parent view appear, MacOS
When a parent view is selected for the detail pane of a NavigationSplitView subviews appear as expected but not with the dimensions set by .frame on the subview. Toggling the flag works as expected, appearing the subview with the idealWidth. I persist the flag in a SwiftData @Model class so that on restart and first appearance of the parent view the Right View subview presence is as it was left. The problem is that the .frame size is ignored, apparently. No manner of programatic view refresh seems to trigger a resize to the preferred values, only toggling the flag. Is there a better way to handle a collapsing subview in an HSplitView? Why is the .frame not respected? In this example I've added the else clause so HSplitView always has two views with .frame settings but the result is the same without it. VStack { HSplitView { VStack { Text("left view") } .frame( minWidth: 100, idealWidth: .infinity, maxWidth: .infinity, maxHeight: .infinity ) if documentSettings.nwIsPieChartShowing { VStack { Text("right view") } .frame( minWidth: 100, idealWidth: 200, maxWidth: .infinity, maxHeight: .infinity ) } else { Text("") .frame( minWidth: 0, idealWidth: 0, maxWidth: 0, maxHeight: .infinity ) } } HStack { Button("Right View", systemImage: { documentSettings.nwIsPieChartShowing ? "chart.pie.fill" : "chart.pie"}(), action: { documentSettings.nwIsPieChartShowing.toggle() } ) } } } } MacOS Sequoia 15.3.1, Xcode 16.2
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
269
Mar ’25
Hover effect is shown on a disabled button
Hello. I have a scenario where a hover effect is being shown for a button that is disabled. Usually this doesn't happen but when you wrap the button in a Menu it doesn't work properly. Here is some example code: struct ContentView: View { var body: some View { NavigationStack { Color.green .toolbar { ToolbarItem(placement: .topBarTrailing) { Menu("Menu") { Button("Disabled Button") {} .disabled(true) .hoverEffectDisabled() // This doesn't work. Button("Enabled Button") {} } } } } } } And here is what it looks like: This looks like a SwiftUI bug. Any help is appreciated, thank you!
1
0
265
Feb ’25