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
401
2w
Who vends the item identifier and the index path arguments to the cell provider closure of a diffable data source?
I was reading over the documentation of the CellProvider struct for the diffable data source initialiser, and the CellProvider is defined as a closure which takes three arguments, a table view, an index path, and an item identifier. My question is, who vends the index path and the item identifier to this closure? My thinking is that it is the data source who vends these items because it adopts the UITableViewDataSource protocol which acts as the source of data for this view.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
192
1d
Add Unity Project to existing VisionOS App
Hello, As titled, my team is trying to find a way to add unity projects to our current developments. We have checked several posts and tutorials, but find they are all about porting to a brand new project. Without modifying too much on our current swift codes, we wonder if we can add Unity part as a WindowGroup/ImmersiveSpace like the following? :) struct TestVisionUnityApp: App { var body: some Scene { // from default template WindowGroup { ContentView() .... } // @TODO WindowGroup {...} } }
0
0
224
1d
Layout Engine Crash on iOS 26: NSInternalInconsistencyException
Starting with iOS 26 beta, I'm encountering an intermittent crash in production builds related to Auto Layout and background threading. This crash did not occur on iOS 18 or earlier and has become reproducible only on devices running iOS 26 betas. We have already performed a thorough audit of our code: • Verified that all UIKit view hierarchy and layout mutations occur on the main thread. • Re-tested with strict logging—confirmed all remaining layout/constraint/view updates are performed on the main thread. • No third-party UI SDKs are used in the relevant flow. Despite that, the crash still occurs and always from a background thread, during internal UIKit layout commits. Fatal Exception: NSInternalInconsistencyException Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread. 0 MyApp 0x7adbc8 FIRCLSProcessRecordAllThreads + 172 1 MyApp 0x7adfd4 FIRCLSProcessRecordAllThreads + 1208 2 MyApp 0x7bc4b4 FIRCLSHandler + 56 3 MyApp 0x7bc25c __FIRCLSExceptionRecord_block_invoke + 100 4 libdispatch.dylib 0x1b7cc _dispatch_client_callout + 16 5 libdispatch.dylib 0x118a0 _dispatch_lane_barrier_sync_invoke_and_complete + 56 6 MyApp 0x7bb1f0 FIRCLSExceptionRecord + 224 7 MyApp 0x7bbd1c FIRCLSExceptionRecordNSException + 456 8 MyApp 0x7badf4 FIRCLSTerminateHandler() + 396 9 Intercom 0x86684 IntercomSDK_sentrycrashcm_cppexception_getAPI + 308 10 libc++abi.dylib 0x11bdc std::__terminate(void (*)()) + 16 11 libc++abi.dylib 0x15314 __cxa_get_exception_ptr + 86 12 libc++abi.dylib 0x152bc __cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) + 90 13 libobjc.A.dylib 0x3190c objc_exception_throw + 448 14 CoreAutoLayout 0x13a4 -[NSISEngine optimize] + 314 15 CoreAutoLayout 0x1734 -[NSISEngine _optimizeWithoutRebuilding] + 72 16 CoreAutoLayout 0x1404 -[NSISEngine optimize] + 96 17 CoreAutoLayout 0xee8 -[NSISEngine performPendingChangeNotifications] + 104 18 UIKitCore 0x27ac8 -[UIView(Hierarchy) layoutSubviews] + 136 19 UIKitCore 0xfe760 -[UIWindow layoutSubviews] + 68 20 UIKitCore 0x234228 -[UITextEffectsWindow layoutSubviews] + 44 21 UIKitCore 0x27674 -[UIImageView animationImages] + 912 22 UIKitCore 0x28134 -[UIView(Internal) _viewControllerToNotifyOnLayoutSubviews] + 40 23 UIKitCore 0x18c2898 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2532 24 QuartzCore 0xabd98 CA::Layer::perform_update_(CA::Layer*, CALayer*, unsigned int, CA::Transaction*) + 116 25 QuartzCore 0x8e810 CA::Layer::update_if_needed(CA::Transaction*, unsigned int, unsigned int) + 600 26 QuartzCore 0xad45c CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 200 27 QuartzCore 0x6e30c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 540 28 QuartzCore 0x9afc4 CA::Transaction::commit() + 644 29 QuartzCore 0x16974c CA::Transaction::release_thread(void*) + 180 30 libsystem_pthread.dylib 0x4c28 _pthread_tsd_cleanup + 620 31 libsystem_pthread.dylib 0x4998 _pthread_exit + 84 32 libsystem_pthread.dylib 0x5e3c pthread_atfork + 54 33 libsystem_pthread.dylib 0x1440 _pthread_wqthread + 428 34 libsystem_pthread.dylib 0x8c0 start_wqthread + 8 Any ideas?
2
1
156
1d
iOS 26 Beta 3 ScrollPosition object not executing scroll commands while scrollPosition(id:) binding works
I'm implementing a horizontal carousel in iOS 26 Beta 3 using SwiftUI ScrollView with LazyHStack. The goal is to programmatically scroll to a specific card on view load. What I'm trying to do: Display a horizontal carousel of cards using ScrollView + LazyHStack Automatically scroll to the "current" card when the view appears Use iOS 26's new ScrollPosition object for programmatic scrolling Current behavior: The ScrollPosition object receives scroll commands (confirmed via console logs) The scrollTo(id:anchor:) method executes without errors However, the ScrollView does not actually scroll - it remains at position 0 Manual scrolling and scrollTargetBehavior(.viewAligned) work perfectly Code snippet: @State private var scrollPositionObject = ScrollPosition() ScrollView(.horizontal) { LazyHStack(spacing: 16) { ForEach(cards, id: .id) { card in CardView(card: card) .id(card.id) } } .scrollTargetLayout() } .scrollPosition($scrollPositionObject) .scrollTargetBehavior(.viewAligned) .onAppear { let targetId = cards[currentIndex].id DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { scrollPositionObject.scrollTo(id: targetId, anchor: .center) } } Workaround that works: Using the iOS 17 scrollPosition(id:) binding instead of the ScrollPosition object: @State private var scrollPosition: UUID? .scrollPosition(id: $scrollPosition) .onAppear { scrollPosition = cards[currentIndex].id } Environment: iOS 26 Beta 3 Xcode 26 Beta 3 Physical device (iPhone 16 Pro Max) Is this a known issue with ScrollPosition in Beta 3, or am I missing something in the implementation? The older binding approach works fine, but I'd prefer to use the new ScrollPosition API if possible.
Topic: UI Frameworks SubTopic: SwiftUI
0
1
61
1d
unselectedItemTintColor of tabBarItem in iOS 26
Hi, I am running iOS Simulator on iOS 26 and I am trying to change unselectedItemTintColor of UITabBarItem in my TabBarViewController but it did not work when I tried following ways: Setting an iconColor through UITabBarAppearance() class Setting unselected item tint color like tabBar.unselectedItemTintColor = .black As an example attached file, I would like to set Settings tab's item color (icon + title) with different one when it is unselected.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
32
1d
New 'badge' property of UIBarButtonItem does not work in iOS 26 beta 3 when used in a toolbar
I'm very happy with the new badge property of UIBarButtonItem, but unfortunately it doesn't work yet on a UIToolbar object. The following code does change the tint color of the button to pink, which proves the button object exists, but there is no visible badge after running the code: if let button = toolbarItems?.first { button.badge = .count(123) // Does nothing button.tintColor = .systemPink // Works } Do I overlook something, or is this just not implemented yet? Or is this limitation 'by design'? (That would be a MAJOR disappointment)
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
53
1d
iOS 26 beta3 Custom keyboard always displays a gray bar above it
Problem description: When using the Custom keyboard in various system application scenarios, a gray area is always displayed at the top of the Custom keyboard. Although the system has been restarted and the Custom keyboard has been restarted, and the pull-down operation has been repeated in multiple system application environments, the gray bar still appears. This problem also has the same problem on other input method software. Reproduction steps: Set the current input method to "CustomKeybaord" In the memo app or any other system app, pull up the Custom keyboard, or switch to the Custom keyboard. Observe whether a gray area is always displayed above the Custom keyboard. Request: I would like to understand whether the current behavior is a bug or if it requires Custom keyboards to adapt their style accordingly. However, I not found that currently unable to modify the style or color of the gray bar in question, and I do not have a suitable adaptation solution at this time. I would appreciate further assistance
Topic: UI Frameworks SubTopic: UIKit
0
0
45
2d
PDFKit findString selection extend not working
With PDFKit in SwiftUI, I'm using the findString function to search the text of a PDF. That part works correctly, but when I use the extend function to get some of the text on both sides of the found word (ie, its context in the page), it doesn't extend. Am I doing this wrong? There is very little documentation or examples about the extend function; even the Apple page doesn't specify what the units refer to in the extend call (presumably it means characters, but I suppose it could also be pixels, or some other measurement specific to PDFs). Here is the code, and pictures of the app, the output (showing that the code can read all the text on the page), and the Acrobat Reader effect I'm trying to achieve. If the extend function truly is broken, and not just a problem in how I'm going about this, a workaround would be to use the text from the entire page, and extract the surrounding words from there, but that does get complicated, especially if there are multiple instances of the word on the page, or if the result straddles 2 pages. import PDFKit import SwiftUI struct ContentView: View { @StateObject var controller = PDFViewController() @State var searchResults:[PDFSelection] = [] var body: some View { VStack { Button { searchResults = controller.pdfView!.document!.findString("is", withOptions: [.caseInsensitive]) let fullPageText = controller.pdfView!.document!.string print(fullPageText) for result in searchResults { let beforeExtending = result.string ?? "" print("Before: \(beforeExtending)") result.extend(atEnd: 3) result.extend(atStart: 3) let afterExtending = result.string ?? "" print("After: \(afterExtending)") } } label: { Text("Do search") } PDFKitView(url: generateURL(), controller: controller) } .padding() } func generateURL() -> URL { let bundlePathRootAsString = Bundle.main.resourcePath! var pdfPathInBundle = URL(fileURLWithPath: bundlePathRootAsString) pdfPathInBundle.append(path: "TestPDF.pdf") return pdfPathInBundle } } struct PDFKitView: UIViewRepresentable { func updateUIView(_ uiView: PDFView, context: Context) { } let url: URL @ObservedObject var controller: PDFViewController func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = PDFDocument(url: self.url) pdfView.autoScales = true controller.pdfView = pdfView return pdfView } } class PDFViewController: ObservableObject { var pdfView: PDFView? }
2
0
95
2d
SwiftData and discarding unsaved changes idea???
Someone smarter than me please tell me if this will work... I want to have an edit screen for a SwiftData class. Auto Save is on, but I want to be able to revert changes. I have read all about sending a copy in, sending an ID and creating a new context without autosave, etc. What about simply creating a second set of ephemeral values in the actual original model. initialize them with the actual fields. Edit them and if you save changes, migrate that back to the permanent fields before returning. Don't have to manage a list of @State variables corresponding to every model field, and don't have to worry about a second model context. Anyone have any idea of the memory / performance implications of doing it this way, and if it is even possible? Does this just make a not quite simple situation even more complicated? Haven't tried yet, just got inspiration from reading some medium content on attributes on my lunch break, and wondering if I am just silly for considering it.
1
0
101
2d
Sheet-like presentation on the side on iPad
Is there a way to get a sheet on the side over an interactive view with a proper glass background on iPad? Ideally, including being able to drag the sheet between medium/large-height sizes (like a sheet with presentationDetents on iPhone), similar to the Maps app: I tried the NavigationSplitView like in the NavigationCookbook example. This is somewhat like it, but it's too narrow (sidebar-like) and doesn't get the full navigation bar: I also played around with .sheet and .presentationDetents and the related modifiers, thinking I could make the sheet appear to the side; but no luck here. It seems to have all the correct behaviors, but it's always presented form-like in the center: Example code for the sheet: import SwiftUI import MapKit struct ContentView: View { var body: some View { Map() .sheet(isPresented: .constant(true)) { NavigationStack { VStack { Text("Hello") NavigationLink("Show Foo") { Text("Foo") .navigationTitle("Foo") .containerBackground(Color.clear, for: .navigation) } } } .presentationDetents([.medium, .large]) .presentationBackgroundInteraction(.enabled) } } } I also tried placing the NavigationStack as an overlay and putting a .glassEffect behind it. From the first sight, this looks okay-ish on beta 3, but seems prone to tricky gotchas and edge cases around the glass effects and related transitions. Seems like not a good approach to me, building such navigational containers myself has been a way too big time-sink for me in the past... Anyway, example code for the overlay approach: import SwiftUI import MapKit struct ContentView: View { var body: some View { Map() .overlay(alignment: .topLeading) { NavigationStack { VStack { Text("Hello") NavigationLink("Show Foo") { ScrollView { VStack { ForEach(1...30, id: \.self) { no in Button("Hello world") {} .buttonStyle(.bordered) } } .frame(maxWidth: .infinity) } .navigationTitle("Foo") .containerBackground(Color.clear, for: .navigation) } } .containerBackground(Color.clear, for: .navigation) } .frame(width: 400) .frame(height: 600) .glassEffect(.regular, in: .rect(cornerRadius: 22)) .padding() } } } Do I miss something here or is this not possible currently with built-in means of the SwiftUI API?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
159
2d
NSInternalInconsistencyException Reason: Modifications to the layout engine must not be performed from a background thread
Hello, We have a Xamarin app in the stores (I know, Xamarin is EOL). We are working on a new version, but do to planning issues, it's not yet ready to be published. We now have a customer who complains that our app is crashing on iOS 26 beta. Our biggest question now is: will it be fixed in the stable release of iOS 26 or will we get a lot of complains around mid September? We currently don't have a device running iOS 26. The crash logs show multiple devices: iPhone 15, iPhone 15 Pro Max and iPhone 16 Pro This is the crash log: Runtime.ThrowNSException (System.IntPtr ns_exception) SIGABRT: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread. Native stack trace: 0 CoreFoundation 0x00000001a2e438dc 44CF748C-19F2-31C4-A0F1-143E32768AF1 + 825564 1 libobjc.A.dylib 0x000000019ffa17a4 objc_exception_throw + 88 2 CoreAutoLayout 0x00000001c9afb3a4 84BC5753-1758-31EE-9293-D54061CA6C7A + 5028 3 CoreAutoLayout 0x00000001c9afb734 84BC5753-1758-31EE-9293-D54061CA6C7A + 5940 4 CoreAutoLayout 0x00000001c9afb404 84BC5753-1758-31EE-9293-D54061CA6C7A + 5124 5 CoreAutoLayout 0x00000001c9afaee8 84BC5753-1758-31EE-9293-D54061CA6C7A + 3816 6 UIKitCore 0x00000001a5a8bac8 ABE178BE-C241-3474-A192-70F042F71BF4 + 162504 7 UIKitCore 0x00000001a5b62760 ABE178BE-C241-3474-A192-70F042F71BF4 + 1042272 8 UIKitCore 0x00000001a5c98228 ABE178BE-C241-3474-A192-70F042F71BF4 + 2310696 9 UIKitCore 0x00000001a5a8b674 ABE178BE-C241-3474-A192-70F042F71BF4 + 161396 10 UIKitCore 0x00000001a5a8c134 ABE178BE-C241-3474-A192-70F042F71BF4 + 164148 11 UIKitCore 0x00000001a7326898 ABE178BE-C241-3474-A192-70F042F71BF4 + 25962648 12 QuartzCore 0x00000001a4db7d98 56B9FC0F-1E8F-3B5F-BE34-7DDB9A5D7375 + 703896 13 QuartzCore 0x00000001a4d9a810 56B9FC0F-1E8F-3B5F-BE34-7DDB9A5D7375 + 583696 14 QuartzCore 0x00000001a4db945c 56B9FC0F-1E8F-3B5F-BE34-7DDB9A5D7375 + 709724 15 QuartzCore 0x00000001a4d7a30c 56B9FC0F-1E8F-3B5F-BE34-7DDB9A5D7375 + 451340 16 QuartzCore 0x00000001a4da6fc4 56B9FC0F-1E8F-3B5F-BE34-7DDB9A5D7375 + 634820 17 Time.iOS 0x0000000105ebb6b0 sqlite3_sourceid + 19991196 18 Time.iOS 0x0000000105dfe4f8 sqlite3_sourceid + 19216612 19 Time.iOS 0x0000000106094154 sqlite3_sourceid + 21927232 20 Time.iOS 0x0000000104efe21c sqlite3_sourceid + 3487240 21 Time.iOS 0x0000000104efb90c sqlite3_sourceid + 3476728 22 Time.iOS 0x0000000104efb70c sqlite3_sourceid + 3476216 23 Time.iOS 0x0000000104efb690 sqlite3_sourceid + 3476092 24 Time.iOS 0x0000000104efe384 sqlite3_sourceid + 3487600 25 Time.iOS 0x00000001051dea20 sqlite3_sourceid + 6503948 26 Time.iOS 0x0000000107a17744 sqlite3_sourceid + 48679728 27 Time.iOS 0x0000000107ad1390 sqlite3_sourceid + 49440636 28 Time.iOS 0x0000000107ad6d2c sqlite3_sourceid + 49463576 29 Time.iOS 0x0000000107b1efe0 sqlite3_sourceid + 49759180 30 Time.iOS 0x0000000107b1ed6c sqlite3_sourceid + 49758552 31 libsystem_pthread.dylib 0x00000002329c9424 _pthread_start + 136 32 libsystem_pthread.dylib 0x00000002329c58cc thread_start + 8 Runtime.ThrowNSException (System.IntPtr ns_exception) Runtime.throw_ns_exception (System.IntPtr exc) (wrapper native-to-managed) ObjCRuntime.Runtime.throw_ns_exception(intptr) (wrapper managed-to-native) ObjCRuntime.Messaging.objc_msgSend(intptr,intptr) CATransaction.Commit () CADisplayLinkTicker.StartThread () ThreadHelper.ThreadStart_Context (System.Object state) ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) ThreadHelper.ThreadStart () (wrapper managed-to-native) ObjCRuntime.Messaging.objc_msgSend(intptr,intptr) CATransaction.Commit () CADisplayLinkTicker.StartThread () ThreadHelper.ThreadStart_Context (System.Object state) ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) ThreadHelper.ThreadStart () kind regards
Topic: UI Frameworks SubTopic: General
0
0
91
2d
Does the canvas view on top of the PDFView not re-render?
I added a canvas view using PDFPageOverlayViewProvider. When I zoom the PDFView, the drawing is scaled, but its quality becomes blurry. How can I fix this? import SwiftUI import PDFKit import PencilKit import CoreGraphics struct ContentView: View { var body: some View { if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf"), let data = try? Data(contentsOf: url), let document = PDFDocument(data: data) { PDFRepresentableView(document: document) } else { Text("fail") } } } #Preview { ContentView() } struct PDFRepresentableView: UIViewRepresentable { let document: PDFDocument let pdfView = PDFView() func makeUIView(context: Context) -> PDFView { pdfView.displayMode = .singlePageContinuous pdfView.usePageViewController(false) pdfView.displayDirection = .vertical pdfView.pageOverlayViewProvider = context.coordinator pdfView.document = document pdfView.autoScales = false pdfView.minScaleFactor = 0.7 pdfView.maxScaleFactor = 4 return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Optional: update logic if needed } func makeCoordinator() -> CustomCoordinator { return CustomCoordinator(parent: self) } } class CustomCoordinator: NSObject, PDFPageOverlayViewProvider, PKCanvasViewDelegate { let parent: PDFRepresentableView init(parent: PDFRepresentableView) { self.parent = parent } func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { let result = UIView() let canvasView = PKCanvasView() canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .blue, width: 20) canvasView.translatesAutoresizingMaskIntoConstraints = false result.addSubview(canvasView) NSLayoutConstraint.activate([ canvasView.leadingAnchor.constraint(equalTo: result.leadingAnchor), canvasView.trailingAnchor.constraint(equalTo: result.trailingAnchor), canvasView.topAnchor.constraint(equalTo: result.topAnchor), canvasView.bottomAnchor.constraint(equalTo: result.bottomAnchor) ]) for subView in view.documentView?.subviews ?? [] { subView.isUserInteractionEnabled = true } result.layoutIfNeeded() return result } }
1
0
129
3d
Section Does Not Seem To Expand/Collapse
This is obviously a user error, but I've been working on different possibilities for a couple of days and nothing works. The problem is my Section in the following code doesn't expand or collapse when I click on the chevron: `class AstroCat { var title: String var contents: [ String ] var isExpanded: Bool init(title: String, contents: [String], isExpanded: Bool) { self.title = title self.contents = contents self.isExpanded = isExpanded } } struct TestView: View { @Binding var isShowingTargetSelection: Bool @State var catalog: AstroCat @State private var expanded = false var body: some View { NavigationStack { List { Section(catalog.title, isExpanded: $catalog.isExpanded) { ForEach(catalog.contents, id: \.self) { object in Text(object) } } } .navigationTitle("Target") .listStyle(.sidebar) } } } #Preview { struct TestPreviewContainer : View { @State private var value = false @State var catalog = AstroCat(title: "Solar System", contents: ["Sun", "Mercury", "Venus", "Earth"], isExpanded: true) var body: some View { TestView(isShowingTargetSelection: $value, catalog: catalog) } } return TestPreviewContainer() }` If I change the "isExpanded: $catalog.isExpanded" to just use the local variable "expanded", then it works, so I think I have the basic SwiftUI pieces correct. But using a boolean inside of the class doesn't seem to work (the section just remains expanded or collapsed based on the initial value of the class variable). Any hints? Am I not specifying the binding correctly? (I've tried a bunch of alternatives) Thanks for the help, Robert
2
0
102
3d