CodexBloom - Programming Q&A Platform

iOS 17: Sudden UI Lag When Using SwiftUI with UIKit Components

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-29
swiftui uikit ios17 combine swift

I'm learning this framework and I'm working on a personal project and I'm facing a significant UI lag in my iOS 17 app when using a combination of SwiftUI and UIKit components. Specifically, I have a view that incorporates a SwiftUI List inside a UIViewController, and the performance seems to degrade dramatically, especially when I scroll through the list. The list updates frequently based on data received from a Combine publisher. When I try to scroll, I can feel the UI stutter and drop frames. I've tried to narrow down the issue by using the Instruments tool, and it shows spikes in CPU usage when the List updates. Here's a simplified version of my code: ```swift import SwiftUI import Combine import UIKit class MyViewController: UIViewController { var cancellable: AnyCancellable? var data: [String] = [] override func viewDidLoad() { super.viewDidLoad() let hostingController = UIHostingController(rootView: MySwiftUIView(data: $data)) addChild(hostingController) view.addSubview(hostingController.view) hostingController.view.frame = view.bounds hostingController.didMove(toParent: self) // Simulating data update cancellable = Just(["Item 1", "Item 2", "Item 3"]) .delay(for: .seconds(1), scheduler: RunLoop.main) .assign(to: &$data) } } struct MySwiftUIView: View { @Binding var data: [String] var body: some View { List(data, id: \.self) { item in Text(item) } } } ``` I've ensured that the data updates are minimal and should not be causing any heavy lifting, but the lag persists. I also tried using `DispatchQueue.main.async` to ensure UI updates are on the main thread, but it didn't help. Is there a known best practice when mixing SwiftUI with UIKit in terms of performance, or are there any common pitfalls that I might be overlooking? Any guidance would be greatly appreciated! My development environment is Ubuntu. I'm developing on Windows 10 with Swift. Thanks for taking the time to read this!