Construct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.

Posts under UIKit tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Memory Leak in Apple TV(tvOS 17.4)
I found a memory leak in tvOS 17.4, but it's not happening in tvOS 18.0 here is the code flow 1.I have controller inside which I have tableView which in turn contains a collectionview here I have passed self to tableViewcell as delegate and then from tableview cell I have passed self again as delegate to collectionViewcell, but memory is not released, because self is retained "I have passed self as weak every where still memory leak is happening only in tvOS 17.4 and below versions. but in 18.0 and above versions it's fine"
1
0
205
1w
iPAD custom in app keyboard stopped responding
IOS 12 - 18.1.1 - objective C, Xcode 16.0 App runs on both iPhone and iPad, this issue only occurs happens on iPads. For the iPhones I am able to get a decent numeric only keyboard to display. I pulled down NumericKeypad from GitHub and used that a model on how to implement a custom keypad. In the inputView of the delegate, a new custom text field is create and then assigned a delegate and other properties then it returns the view to the main ViewController. When the ViewControllers and the correct text field is entered my custom keyboard display and the buttons respond but nothing is displayed in the text field. This has worked for years and all of the sudden it stopped. The original project for the example 10 key custom keyboard builds and when loaded that works on the iPad. If I comment out condition to only execute if running on an iPad and test with an iPhone the keyboards works. It is only on a iPad that this happens. This is the cod that creates creates the keyboard from a .xib file. I am using a storyboard for the main app. #import "Numeric10KeyTextField.h" #import "Numeric10KeyViewController.h" @implementation Numeric10KeyTextField (UIView *)inputView { UIView *view = nil; Numeric10KeyViewController *numVC; // Add hook here for iPhone or other devices if needed but now return nil if iPhone so it uses the default // if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { numVC = [[Numeric10KeyViewController alloc] initWithNibName:@"Numeric10Key" bundle:nil]; [numVC setActionSubviews:numVC.view]; numVC.delegate = self.numeric10KeyDelegate; numVC.numpadTextField = self; view = numVC.view; // } return view; } @end
1
0
197
4d
swiftui fileimporter inside UIHostingController
I'm working on an old iOS app that started with objective-C + UIKit and has being migrated to Swift + SwiftUI. Currently its code is mostly Swift + SwiftUI but it has still some objective-C and some UIKit ViewControllers. One of the SwiftUI views uses fileImporter to open Files App and select a file from the device. This has been working well until iOS 18 is launched. With iOS 18 the file picker is not launching correctly and is frozen in every simulator (the unique real device I've could test with iOS 18 seemed to work correctly). I managed to clone my project and leave it with the minimal amount of files to reproduce this error. This is the code: AppDelegate.h #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> {} @property (strong, nonatomic) UIWindow *window; @end AppDelegate.m #import "AppDelegate.h" #import "MyApp-Swift.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; FirstViewBuilder *viewBuilder = [[FirstViewBuilder alloc] init]; [viewBuilder show]; return YES; } @end FirstViewBuilder.swift import SwiftUI @objc class FirstViewBuilder: NSObject { private var view: UIHostingController<FirstView> @objc override init() { self.view = MyHostingController(rootView: FirstView()) } @objc func show() { let app = UIApplication.shared.delegate as? AppDelegate let window = app?.window window?.backgroundColor = .white // Use navigationController or view directly depending on use window?.rootViewController = view } } FirstView.swift import SwiftUI struct FirstView: View { @State var hasToOpenFilesApp = false var body: some View { VStack(alignment: .leading, spacing: 0) { Button("Open Files app") { hasToOpenFilesApp = true }.fileImporter(isPresented: $hasToOpenFilesApp, allowedContentTypes: [.text]) { result in switch result { case .success(let url): print(url.debugDescription) case .failure(let error): print(error.localizedDescription) } } } } } And finally, MyHostingController import SwiftUI class MyHostingController<Content>: UIHostingController<Content> where Content: View { override init(rootView: Content) { super.init(rootView: rootView) } @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.hidesBackButton = true } } Launching this in an iPhone 13 Pro (18.2) simulator I click on Open Files App, it takes 2 seconds to open it, and it opens full screen (not like a modal). Buttons on the top are behind the status bar and buttons at the bottom are behind the Home indicator. But it's worse because the user can't interact with this view, it's frozen. I created a fresh SwiftUI project just with this unique view and the fileimport worked as expected so I thought the problem was due to embed the SwiftUI view inside the UIHostingController. So I made these modifications to the minimal project: Remove the files AppDelegate, FirstViewBuilder and MyHostingController. Create this SwiftUI App file import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { FirstView() } } } And again the same problem with iOS 18. But if I launch this exact project in an iPhone 13 Pro (17.4) simulator and open the files apps (now it opens almost instantly) it works OK and shows the file picker as a modal, as expected, and I can interact with it and select files. Last thing I've tried is removing LaunchScreen.xib from my project and Launch screen interface file base name key from my info.plist but the problem keeps happening. I guess it must be due to my project configuration (too old) but I have no more ideas of where to look at. The possibility of having a fresh SwiftUI project and "move" the old project to the new one could take me several weeks and I discard it by the moment. Could I use another method to select files from SwiftUI views with iOS 18?
2
0
270
1w
SwiftUI navigationDestination will make child view's stateObject init multi times with sheet modifier.
Below is my sample code. On the Home page, when I click "show sheet," the sheet page expands, and the StateObject inside the sheet is initialized once. However, when I click "show Fullscreen" and then click "show sheet" inside the fullscreen page, the sheet gets initialized twice. However, if I remove navigationDestination, this issue does not occur. This problem causes the network request in the sheet page to be triggered multiple times. Can someone tell me the reason? enum TestRouter: String, Hashable { case test var targetView: some View { Text("test") } var title: String { return "test title" } } @MainActor struct NavigationInnerView<Content>: View where Content: View { var contentView: () -> Content @MainActor public init(@ViewBuilder contentView: @escaping () -> Content) { self.contentView = contentView } var body: some View { NavigationStack() { contentView() .navigationDestination(for: TestRouter.self) { route in route.targetView } } .navigationViewStyle(StackNavigationViewStyle()) } } struct ContentView: View { @State var showFullScreen: Bool = false @State var showSheet: Bool = false var contentView: some View { VStack { VStack { Text("Home") Button { showFullScreen = true } label: { Text("show fullscreen") } Button { showSheet = true } label: { Text("show sheet ") } } } } var body: some View { NavigationInnerView { contentView .fullScreenCover(isPresented: $showFullScreen) { NavigationInnerView { FullScreenContentView() } } .sheet(isPresented: $showSheet) { NavigationInnerView { SheetContentView() } } } } } class FullScreenViewModel: ObservableObject { @Published var content: Bool = false init() { print("Full Screen ViewModel init") } } struct FullScreenContentView: View { @Environment(\.dismiss) var dismiss @State var showSheet: Bool = false @StateObject var viewModel: FullScreenViewModel = .init() init() { print("Full screen view init") } var body: some View { VStack { Text("FullScreen") Button { dismiss() }label: { Text("dismiss") } Button { showSheet = true } label: { Text("show sheet") } } .sheet(isPresented: $showSheet) { NavigationInnerView { SheetContentView() } } } } class SheetViewModel: ObservableObject { @Published var content: Bool = false init() { print("SheetViewModel init") } } struct SheetContentView: View { @Environment(\.dismiss) var dismiss @StateObject var viewModel = SheetViewModel() init() { print("sheet view init") } var body: some View { Text("Sheet") Button { dismiss() } label: { Text("dismiss") } } } #Preview { ContentView() }
3
0
215
2w
CollectionView: Sync `center.y` of UIView outside collection view and a view in a cellinside
I have a setup: Collection view with compositional layout a self sizing cell inside a subview inside the cell and unrelated view outside the collection view I would like to: modify the layout (constraints) of the cell inside the collection view with UIView.animate trigger an animated layout update of collection view synchronize the position of an unrelated view to the position of one of the subviews of a collection view cell What I tried: UIView.animate(withDuration: 0.25) { cellViewReference.updateState(state: state, animated: false) collectionView.collectionViewLayout.invalidateLayout() collectionView.layoutIfNeeded() someOtherViewOutsideCollectionView.center = cellViewReference.getPositionOfThatOneViewInWindowCoordinateSystem() } What I'm expecting: after invalidateLayout, the layout update of the collection view is merely scheduled, but not yet performed layoutIfNeeded forces an update on the collectionViewLayout + update on the frames of the views inside the UICollectionViewCells all the frames become correct to what they will look like after the animation is performed I call getPositionOfThatOneViewInWindowCoordinateSystem and it gives me the position of the view after the uicollectionview AND the cell's layout has updated What happens instead: getPositionOfThatOneViewInWindowCoordinateSystem returns me an old value I am observing that the bounds of the cell didn't actually change during layoutIfNeeded And moreover, the bounds change without animation, instantly Question: how to animate self sizing cell size change due relayout how to synchronize outside views with collection views
1
0
192
2w
UICollectionView.CellRegistration and dequeueConfiguredReusableCell with nil for Item? causes runtime crash
Modern collection views use UICollectionViewDiffableDataSource with UICollectionView.CellRegistration and UICollectionView.dequeueConfiguredReusableCell(registration:indexPath:item). There are runtime crashes when passing nil as argument for the item parameter. There's no clear documentation on whether optional items are allowed or not. The function signature in Swift is: @MainActor @preconcurrency func dequeueConfiguredReusableCell<Cell, Item>(using registration: UICollectionView.CellRegistration<Cell, Item>, for indexPath: IndexPath, item: Item?) -> Cell where Cell : UICollectionViewCell Given the Item? type one would assume Optionals are allowed. In Objective-C the signature is: - (__kindof UICollectionViewCell *)dequeueConfiguredReusableCellWithRegistration:(UICollectionViewCellRegistration *)registration forIndexPath:(NSIndexPath *)indexPath item:(id)item; I'm not sure, if there's implicit nullability bridging to the Swift API or if the Objective-C files has some explicit nullability annotation. The crash is due to a swift_dynamicCast failing with: Could not cast value of type '__SwiftNull' (0x10b1c4dd0) to 'Item' (0x10d6086e0). It's possible to workaround this by making a custom Optional type like enum MyOptional<T> { case nothing case something(T) } and then wrapping and unwrapping Item? to MyOptional<Item>. But this feels like unnecessary boilerplate. With the current situation it's easy to ship an app where everything seems to work, but in production only certain edge cases cause nil values being used and then crashing the app. Please clarify the allowed arguments / types for the dequeueConfiguredReusableCell function. Either Optionals should be supported and not crash at runtime or the signatures should be changed so there's a compile time error, when trying to use an Item?. Feedback: FB16494078
3
1
211
1w
SFSafariViewController's preferred colors are invalidated after rotation
There are two issues about SFSafariViewController. After rotate from landscape to portrait, The topAnchor is destroyed. The specified bar tint color and control tint color are invalidated.(Returns to system color) Regarding the second issue, I’ve found a temporary workaround. Override the viewWillTransition(to:with:) and keep it empty. Don't call super.viewWillTransition(to:with:). Since UIKit is not open source, I don’t know the exact cause, but I found something that could be the key to the issue. So, I reported it to Apple Feedback Assistant. You can check the details and the sample project in the GitHub repository below. https://github.com/ueunli/SafariViewer
0
0
169
2w
iOS Architecture Research - Help a student
Hi everyone! I'm thrilled to share that I'm conducting a field research as part of my final university project, focused on iOS architecture. The goal is to dive deeper into the best practices, challenges, and trends in the iOS development world. To make this research truly impactful, I need your help! If you're an iOS developer, I’d love it if you could take a few minutes to answer a short survey. Your insights and experiences will be invaluable for my research, and I greatly appreciate your support! Here is the link: https://docs.google.com/forms/d/e/1FAIpQLSdf9cacfA7my1hnlazyl7uJraa2oTsQ7dJBWvFtZ_4vbYenRA/viewform?usp=send_form Thank you so much in advance for helping me out—feel free to share this post with others who might also be interested. Let’s build something amazing together! 💡✨
0
0
182
3w
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
223
3w
Getting a file icon on iOS
Some time ago I read somewhere that one can get a file icon on iOS like this: UIDocumentInteractionController(url: url).icons.last!) but this always returns the following image for every file: Today I tried the following, which always returns nil: (try? url.resourceValues(forKeys: [.effectiveIconKey]))?.allValues[.effectiveIconKey] as? UIImage Is there any way to get a file icon on iOS? You can try the above methods in this sample app: struct ContentView: View { @State private var isPresentingFilePicker = false @State private var url: URL? var body: some View { VStack { Button("Open") { isPresentingFilePicker = true } if let url = url { Image(uiImage: UIDocumentInteractionController(url: url).icons.last!) if let image = (try? url.resourceValues(forKeys: [.effectiveIconKey]))?.allValues[.effectiveIconKey] as? UIImage { Image(uiImage: image) } else { Text("none") } } } .padding() .fileImporter(isPresented: $isPresentingFilePicker, allowedContentTypes: [.data]) { result in do { let url = try result.get() if url.startAccessingSecurityScopedResource() { self.url = url } } catch { preconditionFailure(error.localizedDescription) } } } }
2
0
264
3w
Set UILabel color in alertController
I have an alertController that is presented as popover on iPad let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: alertStyle) if let ppc = alertController.popoverPresentationController { // … } Is it possible to change the message font color (which is really very light on iPad) ? It is OK on iPhone with the same alert (not popover): text is much more readable:
1
0
210
2w
Apple Maps annotations and markers
In Apple's Maps app, an annotation is made up of a circle shape or rounded rectangles with a glyph-image. When selecting an annotation, the annotation animates into a balloon marker (see attached GIF). How does Apple Maps solve this - from custom annotation to balloon marker with spring animation? I switched my Maps implementation from SwiftUI to UIKit with a UIViewRepresentable to support annotation clustering - and it works beautifully. But how to subclass an MKAnnotationView (or MKMarkerAnnotationView <- the balloon) to enable selection and animation as in Apple Maps? MKMarkerAnnotationView only show balloon markers and I tried everything inside MKAnnotationView (CALayer, etc.)
1
0
224
3w
App crashes when the app is moved to background
After the app is put in background for sometime and the app crashes, Some cases have the webView involvement before putting the app in to background for quite sometime and pulled into foreground. Here's the crash log information. Identifier: com.app.myapp Version: 2.3.3 (30) AppStoreTools: 16C5031b AppVariant: 1:iPhone9,1:15 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.app.myapp [2833] Date/Time: 2024-12-12 17:30:57.4489 +0100 Launch Time: 2024-12-12 17:04:19.7290 +0100 OS Version: iPhone OS 15.5 (19F77) Release Type: User Baseband Version: 9.61.00 Report Version: 104 **Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000018f1358e0 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [82527] Triggered by Thread: 10 Kernel Triage: VM - Fault hit memory shortage** Thread 10 Crashed: 0 WebKit 0x000000018f1358e0 WTFCrashWithInfo(int, char const*, char const*, int) + 20 (Assertions.h:732) 1 WebKit 0x000000018f72e348 WebKit::allDataStores() + 72 (WebsiteDataStore.cpp:100) 2 WebKit 0x000000018f72e278 WebKit::WebsiteDataStore::forEachWebsiteDataStore(WTF::Function<void (WebKit::WebsiteDataStore&)>&&) + 24 (WebsiteDataStore.cpp:107) 3 WebKit 0x000000018f67c440 WebKit::WebProcessPool::updateProcessAssertions() + 52 (WebProcessPool.cpp:1773) 4 WebKit 0x000000018f684508 WebKit::WebProcessProxy::didSetAssertionType(WebKit::ProcessAssertionType) + 880 (Function.h:82) 5 WebKit 0x000000018f5bfdd0 WebKit::ProcessThrottler::setAssertionType(WebKit::ProcessAssertionType) + 712 (ProcessThrottler.cpp:148) 6 WebKit 0x000000018f5bf9b4 WebKit::ProcessThrottler::updateAssertionIfNeeded() + 408 (ProcessThrottler.cpp:176) 7 WebKit 0x000000018f5c42b0 WebKit::ProcessThrottler::Activity<(WebKit::ProcessThrottler::ActivityType)1>::Activity(WebKit::ProcessThrottler&, WTF::ASCIILiteral) + 76 (ProcessThrottler.cpp:58) 8 WebKit 0x000000018f659958 WebKit::WebPageProxy::runJavaScriptInFrameInScriptWorld(WebCore::RunJavaScriptParameters&&, std::__1::optional<WTF::ObjectIdentifierWebCore::FrameIdentifierType >, API::ContentWorld&, WTF::Comple... + 240 (ProcessThrottler.h:66) 9 WebKit 0x000000018f3ca7cc -[WKWebView _evaluateJavaScript:asAsyncFunction:withSourceURL:withArguments:forceUserGesture:inFrame:inWorld:completionHandler:] + 1352 (WKWebView.mm:1151) 10 WebKit 0x000000018f131700 -[WKWebView evaluateJavaScript:completionHandler:] + 120 (WKWebView.mm:896) 11 MyApp 0x00000001044e7e64 cli_signalHandler + 2420 12 MyApp 0x00000001044e4470 getExtraInfoId + 132792 13 MyApp 0x00000001044c2b18 CLI_Reset + 50684 14 MyApp 0x00000001044c2a18 CLI_Reset + 50428 15 MyApp 0x00000001044c1cec CLI_Reset + 47056 16 MyApp 0x00000001044c27e8 CLI_Reset + 49868 17 MyApp 0x00000001044e01f4 getExtraInfoId + 115772 18 MyApp 0x0000000104492498 StringToScreenDensityLevel + 4588 19 libdispatch.dylib 0x0000000180e80094 _dispatch_client_callout + 16 (object.m:560) 20 libdispatch.dylib 0x0000000180e22bb8 _dispatch_continuation_pop$VARIANT$mp + 440 (inline_internal.h:2622) 21 libdispatch.dylib 0x0000000180e348dc _dispatch_source_invoke$VARIANT$mp + 1668 (source.c:596) 22 libdispatch.dylib 0x0000000180e22730 _dispatch_queue_override_invoke + 424 (queue.c:0) 23 libdispatch.dylib 0x0000000180e2fb94 _dispatch_root_queue_drain + 340 (inline_internal.h:0) 24 libdispatch.dylib 0x0000000180e3039c _dispatch_worker_thread2 + 172 (queue.c:6935) 25 libsystem_pthread.dylib 0x00000001dc483dd4 _pthread_wqthread + 224 (pthread.c:2612) 26 libsystem_pthread.dylib 0x00000001dc48393c start_wqthread + 8 (:-1) Thread 10 crashed with ARM Thread State (64-bit): x0: 0x0000000000000064 x1: 0x000000018fad60a0 x2: 0x000000018fad6189 x3: 0x0000000000000113 x4: 0x0000000000000030 x5: 0x0000000100000030 x6: 0x0000000000000000 x7: 0x0000000000000001 x8: 0x000000016fd6b000 x9: 0x0000000106dd4580 x10: 0x000000000000002c x11: 0x0000000000020408 x12: 0x0000000000080000 x13: 0x0000000000000000 x14: 0x0000020000011000 x15: 0x0000000100000000 x16: 0x00000001dc48425c x17: 0x0000000000000000 x18: 0x0000000000000000 x19: 0x000000016fd6a418 x20: 0x0000000282ece080 x21: 0x00000002834ac2a0 x22: 0x00000001f694c000 x23: 0x0000000117004a80 x24: 0x0000000283bb6558 x25: 0x000000011a00a1d8 x26: 0x0000000000000000 x27: 0x0000000000000002 x28: 0x000000016fd6b180 fp: 0x000000016fd6a3d0 lr: 0x000000018f72e348 sp: 0x000000016fd6a3b0 pc: 0x000000018f1358e0 cpsr: 0x60000000 esr: 0xf200c471 (Breakpoint) pointer authentication trap IB
2
0
223
3w
Extending iOS screen to an external display
I understand two key concepts from desktop platforms: Screen Mirroring – The same content is displayed on both the primary and external screens. Screen Extension – The external display shows different content that complements what's on the main screen. My question pertains to the second point: Is it possible to extend the display on iOS and iPadOS devices? I'm referring to this Apple documentation, which explains how to extend content from an iOS/iPadOS device to an external display. I tested this in a sample iOS Xcode project. In the iOS Simulator, I was able to detect an "external display" and present a separate UIWindow on it. However, when I tried the same on a real device (iPhone 15 connected to a MacBook Pro via cable), the external display connection was not detected. I’d like to confirm whether screen extension is possible on a real iOS device. From my research, it appears that extension is only supported on iPadOS via Stage Manager, but I want to verify if there’s any way to achieve this on an iPhone. If so, are there any known apps that currently utilize extended display functionality on iOS? If extension is not possible on iOS, what does the documentation mentions iOS?
1
0
241
3w
labels appear as dimmed in UIView
In this setup, label do not show properly because of the textColor. Labels are defined in IB, in the following hierarchy: ViewController View Label 1 scrollView View Button Label 2 Buttons show properly, but labels, even though defined with default label color appear as if their alpha was 0.2. It is even worse in dark mode: I have checked the settings for the label and did not find anything anormal: I have tried to change label color to system.gray 2, to no avail. If I change to red, does not show in red in IB. Problem appears for both Label 1 (at the top level in the view) and Label 2
1
0
218
3w
WKWebView: Select Text and scroll beyond what's visible
Prime Objective I am trying to have a scroll view with a fixed header, a fixed footer, and a WKWebView in between. Using JavaScript, the height of the webView is determined and set to be large enough to hold the entire content. The Problem When selecting text on the webView, the view does not scroll when the edges are reached (this works if the webView is shown without being embedded in a Scroll view, or if it is the last element) What did I try? I tried reading the scroll view, or adding a gesture recognizer, but all of that does not work because the selection is essentially a system task Sourcecode Sourcecode to demonstrate the issue can be found on GitHub
0
0
197
4w
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
202
2d