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

How to detect UIScreen changes in a UIView subclass?
I'm looking for a reliable way to detect when the UIScreen of a UIView changes. I'm developing a renderer SDK that provides a custom UIView subclass which performs OpenGL / Metal rendering, driven by a CADisplayLink. To support scenarios like screen mirroring or external displays on iPad, I need to ensure the CADisplayLink is created using the correct UIScreen, so the refresh rate is accurate. Ideally, I’d like a way to be notified in the view itself (without requiring scene delegate integration) whenever self.window.windowScene.screen changes, even if trait values remain the same. Any ideas or workarounds that work safely in production would be hugely appreciated! Since iOS 13, the architecture is: The app can have multiple UIScene instances (typically UIWindowScene). Each UIWindowScene can have multiple UIWindows. Each UIWindow hosts a view hierarchy. To determine the correct UIScreen, I access self.window.windowScene.screen. If any component in that key path changes (window, windowScene, or screen), I need to detect it and react. Here’s what I’ve tried so far: Overriding willMoveToWindow: and didMoveToWindow: This allows me to detect changes to window, but if windowScene (of the window) or screen (of the scene) changes directly, I get no notification. Overriding traitCollectionDidChange: This works if the screen change causes a difference in traits (e.g., a different displayScale), but fails if the old and new screens share the same traits (e.g., identical scale). Listening to UIScene-related notifications Notifications like UISceneDidDisconnectNotification or UISceneWillEnterForegroundNotification only indicate scene lifecycle events, not that a particular view or window has moved to a different screen. Using KVO to observe self.window.windowScene.screen I found WebKit does something similar, but in practice this causes crashes. The error message suggests that "windowScene" is not KVO-compliant, and my experience confirms it's not safe in production. Apple's official guidance uses UIWindowSceneDelegate In this example, Apple shows how to update a CADisplayLink in a UIWindowSceneDelegate's windowScene:didUpdateCoordinateSpace:interfaceOrientation:traitCollection:. However, as an SDK provider delivering just a UIView, I don't have control over the host app's UIWindowSceneDelegate.
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
63
4w
Use Custom UIApplication Subclass with SwiftUI
I have a SwiftUI app which needs the Ivanti AppConnect SDK. The docs only show how to integrate it into a Swift/UIKit app. But I need it to work with SwiftUI. I probably could make a UIKit base app and then load my existing SwiftUI views and code through a SwiftUI component host or something. But I'd like to avoid that if possible. Here is where I'm stuck: The AppConnect framework loads through a custom UIApplication subclass in the main.swift file: import Foundation import AppConnect UIApplicationMain( CommandLine.argc, CommandLine.unsafeArgv, ACUIApplicationClassName, NSStringFromClass(AppDelegate.self) ) The startup works as expected, and the expected function is called in the AppDelegate class: func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {...} However, the SwiftUI view is not loaded and the scree stays blank. I implemented a SceneDelegate.swift class which doesn't seem to be called. Also, the following function in the AppDelegate doesn't get called either: func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {...} So how do I bootstrap SwiftUI with a custom UIApplication class? can that be done with the @main macro somehow? I'm still pretty new to Swift and iOS development. Any help is appreciated
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
24
May ’25
How to Get Device Orientation in Background (PiP) Mode?
My app is a camera app that supports Picture-in-Picture (PiP) mode. Normally, when the device rotates, I get the device orientation from iOS and use it to rotate the camera feed so that the preview stays correctly aligned. However, when the app enters PiP mode, it is considered to be in the background, and I can no longer receive orientation updates from the system. As a result, I can’t apply rotation corrections to the camera video in PiP mode. Is there any way to retrieve device orientation while the app is in the background (specifically during PiP mode)? Any guidance would be greatly appreciated. Thank you!
0
0
31
May ’25
how to get subviews of a SwiftUI view in UIKit environment
I have a SwiftUI view that I have wrapped using UIHostingController for use within UIKit. Requirement: Within the UIKit environment, I want to get all the subviews of this SwiftUI view and determine whether the images within those subviews have finished loading. For UIKit views, we can use view.subviews to get all the subviews and do the check. However, for SwiftUI views, I found that the view.subviews turns out to be an empty array, making it impossible to do further checks. So the question is How can I get the subviews of a SwiftUI view?
2
0
55
May ’25
App Terminated with 0x8BADF00D: Main Thread Blocked During Back-to-Back Messaging
Hello, I'm experiencing an issue with my app where it's being terminated by the system with a watchdog violation during back-to-back messaging operations. I've analyzed the crash logs but would appreciate additional insights on optimizing my approach. I'd appreciate any insights on how to resolve this problem. Crash Details: Exception Type: EXC_CRASH (SIGKILL) Termination Reason: FRONTBOARD with code 0x8BADF00D Error: "scene-update watchdog transgression: app exhausted real time allowance of 10.00 seconds" Reproduction Steps: User A initiates back-to-back messages to other User User A's UI becomes unresponsive and eventually the app crashes. Stack Trace Analysis: The crash occurs on the main thread, which appears to be blocked waiting for a condition in the keyboard handling system. The thread is stuck in [UIKeyboardTaskQueue _lockWhenReadyForMainThread] and related methods, suggesting an issue with keyboard-related operations during the messaging process. Crash Tag Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.msikodiak.eptt(AD934F8A-DF57-4B75-BE73-8CF1A9A8F856)>:301 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Foreground ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 6.390 (user 3.640, system 2.750), 11% CPU", "Elapsed application CPU time (seconds): 0.020, 0% CPU" ) ThermalInfo: ( "Thermal Level: 0", "Thermal State: nominal" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1e773d438 __psynch_cvwait + 8 1 libsystem_pthread.dylib 0x2210bc328 _pthread_cond_wait + 1028 2 Foundation 0x1957d8a64 -[NSCondition waitUntilDate:] + 132 3 Foundation 0x1957d8888 -[NSConditionLock lockWhenCondition:beforeDate:] + 80 4 UIKitCore 0x1998f1238 -[UIKeyboardTaskQueue _lockWhenReadyForMainThread] + 456 5 UIKitCore 0x19a3d775c __59-[UIKeyboardImpl updateAutocorrectPrompt:executionContext:]_block_invoke_9 + 28 6 UIKitCore 0x19986b084 -[UIKeyboardTaskQueue lockWhenReadyForMainThread] + 168 7 UIKitCore 0x19a3f2994 -[UIKeyboardTaskQueue waitUntilTaskIsFinished:] + 148 8 UIKitCore 0x19a3f2ac4 -[UIKeyboardTaskQueue performSingleTask:breadcrumb:] + 132 9 UIKitCore 0x199e2f7e4 -[_UIKeyboardStateManager updateForChangedSelection] + 144 10 UIKitCore 0x199e24200 -[_UIKeyboardStateManager invalidateTextEntryContextForTextInput:] + 92 11 WebKit 0x1ad52fa54 WebKit::PageClientImpl::didProgrammaticallyClearFocusedElement(WebCore::ElementContext&&) + 40 12 WebKit 0x1ad55adcc WebKit::WebPageProxy::didProgrammaticallyClearFocusedElement(WebCore::ElementContext&&) + 136 13 WebKit 0x1acec74e8 WebKit::WebPageProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 18604 14 WebKit 0x1acd21184 IPC::MessageReceiverMap::dispatchMessage(IPC::Connection&, IPC::Decoder&) + 236 15 WebKit 0x1ace449b8 WebKit::WebProcessProxy::dispatchMessage(IPC::Connection&, IPC::Decoder&) + 40 16 WebKit 0x1ace44228 WebKit::WebProcessProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 1764 17 WebKit 0x1acd1e904 IPC::Connection::dispatchMessage(WTF::UniqueRef<IPC::Decoder>) + 268 18 WebKit 0x1acd1e478 IPC::Connection::dispatchIncomingMessages() + 576 19 JavaScriptCore 0x1ae386b8c WTF::RunLoop::performWork() + 524 20 JavaScriptCore 0x1ae386960 WTF::RunLoop::performWork(void*) + 36 21 CoreFoundation 0x196badce4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 22 CoreFoundation 0x196badc78 __CFRunLoopDoSource0 + 172 23 CoreFoundation 0x196bac9fc __CFRunLoopDoSources0 + 232 24 CoreFoundation 0x196babc3c __CFRunLoopRun + 840 25 CoreFoundation 0x196bd0700 CFRunLoopRunSpecific + 572 26 GraphicsServices 0x1e3711190 GSEventRunModal + 168 27 UIKitCore 0x1997ee240 -[UIApplication _run] + 816 28 UIKitCore 0x1997ec470 UIApplicationMain + 336 29 Telstra PTT 0x1004d30c8 main + 56 30 dyld 0x1bd5d3ad8 start + 5964
2
0
68
3w
App Name Display
For now, my app name length is more than 20 characters, so the iPhone app name displays without a space, and uses the range operator to ensure showing the rest in the next line. Is it possible to show space and name with 2 lines?
Topic: UI Frameworks SubTopic: General Tags:
0
0
29
May ’25
How to Create Applications with Objective-C Without ARC
I've been teaching myself Objective-C and I wanted to start creating projects that don't use ARC to become better at memory management and learn how it all works. I've been attempting to build and run applications, but I'm not really sure where to start as modern iOS development is used with Swift and memory management is handled. Is there any way to create modern applications that use Objective-C, UIKit, and not use ARC?
3
0
116
May ’25
Crash/Glitch when using setViewControllers(_:animated:) with UIHostingController and .refreshable in SwiftUI
Introduction Hello, As part of our ongoing migration to SwiftUI, we are currently managing navigation using UIKit. Our SwiftUI views are embedded in UIHostingController instances and pushed or presented via UINavigationController. We’ve encountered an issue that causes either a UI glitch on iOS 18 or a crash on iOS 17 when using the .refreshable modifier in a SwiftUI view that is added to a UINavigationController via setViewControllers(_:animated:). To reproduce the issue, we’re using the following simple SwiftUI view: struct TestView: View { var body: some View { List { ForEach(0...100, id: \.self) { Text("Number: \($0)") } } .refreshable { // No action needed — the presence of this modifier alone triggers the issue } } } Problematic Scenario The following code causes the issue: class ViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let initialNav = self.navigationController let hostingController = UIHostingController(rootView: TestView()) let newNav = UINavigationController() // This causes a freeze (iOS 18) or crash (iOS 17) newNav.setViewControllers([hostingController], animated: true) initialNav?.present(newNav, animated: true) } } After presenting the navigation controller, our app is freezing on iOS 18 or crashing on iOS 17. Working scenario When using pushViewController(_:animated:), the issue does not occur: class ViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let initialNav = self.navigationController let hostingController = UIHostingController(rootView: TestView()) let newNav = UINavigationController() // This works without issue newNav.pushViewController(hostingController, animated: true) initialNav?.present(newNav, animated: true) } } Conclusion We would like to better understand the root cause of this behavior. While using pushViewController is a viable workaround, there are scenarios where we must rely on setViewControllers, and currently, that approach breaks the experience or crashes the app. Is this a known issue, or are we missing something about how UIHostingController interacts with .refreshable in this context? Thanks for your time — we look forward to any insights you can share.
2
0
118
May ’25
How to prevent iOS VoiceOver from speaking accessibility-labels and traits?
I have a button with the following properties: accessibilityLabel: "Action Button", traits: "Button", accessibilityHint: "Performs the main action". The voiceover reads the button as follows: Action Button, Button, Performs the main action. I want to understand how to configure it to only speak the accessibilityHint or only the accessibilityLabel and never speak the traits. In another example, a switch has the traits: Button, and Toggle. So these traits are a part of what the voiceover speaks. I want only the accessibilityLabel or accessibilityHint to be spoken in this case. Please let me know how. Thanks
1
0
45
May ’25
Tab bar inline icon text .compact mode in size classes in iPad in iOS 18..4.1
I am trying to do inline to icon and text in tab bar but it is not allowing me to do it in compact, but it showing me in regular mode , but in regular mode tab bar going at top in portrait mode , But my requirement is tab bar required in bottom with icon and text in inline it showed by horizontally but it showing to me stacked vertically, will you guide me on this so that I can push the build to live users.
0
0
48
May ’25
Behavior of Drawings in Portrait/Landscape Mode
The app provides a simple drawing functionality on a canvas without using a storyboard. After creating drawings in portrait mode, rotating the simulator or the iPad-Device to landscape mode does not update or rescale the existing drawings to fit the newly expanded canvas area. The app can also be launched directly in landscape mode, allowing drawings to be created before rotating the device back to portrait mode. However, the issue persists, with the drawings not adjusting to the new canvas dimensions. The goal is to achieve the same behavior as in the Apple Notes app: when the iPad is rotated, the drawings should adjust to the newly expanded or reduced canvas area. I would appreciate any suggestions or solutions. Sample Projekt [https://github.com/GG88IOS/Test_Drawing_App)
4
0
75
May ’25
App Crashes on Paper Selection After Background Printer Connection
Description: 1. When initiating the print flow via UIPrintInteractionController, and no printer is initially connected, iOS displays all possible paper sizes in the paper selection UI. However, if a printer connects in the background after this view is shown, the list of paper sizes does not automatically refresh to reflect only the options supported by the connected printer. 2. If the user selects an incompatible paper size (one not supported by the printer that has just connected), the app crashes due to an invalid configuration. Steps to Reproduce: Launch the app and navigate to the print functionality. Tap the Print button to invoke UIPrintInteractionController. At this point, no printer is yet connected. iOS displays all available paper sizes. While the paper selection UI is visible, the AirPrint-compatible printer connects in the background. Without dismissing the controller, the user selects a paper size (e.g., one that is not supported by the printer). The app crashes. Expected Result: App should not crash Once the printer becomes available (connected in the background), the paper size options should refresh automatically. The list should be filtered to only include sizes that are compatible with the connected printer. This prevents the user from selecting an invalid option, avoiding crashes. Actual Result: App crashes The paper size list remains unfiltered. The user can still select unsupported paper sizes. Selecting an incompatible option causes the app to crash, due to a mismatch between UI selection and printer capability. Demo App Crash : https://drive.google.com/file/d/19PV02wzOJhc2DYI6kAe-uxHuR1Qg15Bu/view?usp=sharing Apple Files App Crash: https://drive.google.com/file/d/1flHKuU_xaxHSzRun1dYlh8w7nBPJZeRb/view?usp=sharing
0
0
17
Apr ’25
Xcode UIKit Document App template crashes under Swift 6
I'm trying to switch to UIKit's document lifecycle due to serious bugs with SwiftUI's version. However I'm noticing the template project from Xcode isn't compatible with Swift 6 (I already migrated my app to Swift 6.). To reproduce: File -> New -> Project Select "Document App" under iOS Set "Interface: UIKit" In Build Settings, change Swift Language Version to Swift 6 Run app Tap "Create Document" Observe: crash in _dispatch_assert_queue_fail Does anyone know of a work around other than downgrading to Swift 5?
0
1
40
Apr ’25
How to detect iPad trackpad touch-down (indirectPointer) to immediately stop coasting animation
Hello, I have a custom 3D object viewer on iOS that lets users spin the model using the touchscreen or a trackpad and supports coasting (momentum spinning). I need to stop the coasting animation as soon as the user touches down, but I can only immediately detect touches on the screen itself - on the trackpad I can't get an immediate notification of the touches. So far I’ve tried: State.began on my UIPanGestureRecognizer. It only fires after a small movement on both touchscreen and trackpad. .possible on the pan gesture; this state never occurs during the gesture cycle. UIApplicationSupportsIndirectInputEvents = YES in Info.plist; it didn’t make touchesBegan fire for indirectPointer touches. Since UITableView (and other UIScrollView subclasses) clearly detect trackpad “touch-down” to cancel scrolling, there must be a way to receive that event. Does anyone know how to catch the initial trackpad contact—before any movement—on an indirect input device? Below is a minimal code snippet demonstrating the issue. On the touchscreen you'll see a message the moment you touch the view, but the trackpad doesn't trigger any messages until your fingers move. Any advice would be greatly appreciated. Thanks in advance, John import UIKit class ViewController: UIViewController { private let debugView = DebugView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // Fill the screen with our debug view debugView.frame = view.bounds debugView.autoresizingMask = [.flexibleWidth, .flexibleHeight] debugView.backgroundColor = UIColor(white: 0.95, alpha: 1) view.addSubview(debugView) // Attach a pan recognizer that logs its state let panGR = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) panGR.allowedScrollTypesMask = .all debugView.addGestureRecognizer(panGR) } @objc private func handlePan(_ gr: UIPanGestureRecognizer) { switch gr.state { case .possible: print("Pan state: possible") case .began: print("Pan state: began") case .changed: print("Pan state: changed – translation = \(gr.translation(in: debugView))") case .ended: print("Pan state: ended – velocity = \(gr.velocity(in: debugView))") case .cancelled: print("Pan state: cancelled") case .failed: print("Pan state: failed") @unknown default: print("Pan state: unknown") } } } class DebugView: UIView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) for t in touches { let typeDesc: String switch t.type { case .direct: typeDesc = "direct (finger)" case .indirectPointer: typeDesc = "indirectPointer (trackpad/mouse)" case .indirect: typeDesc = "indirect (Apple TV remote)" case .pencil: typeDesc = "pencil (Apple Pencil)" @unknown default: typeDesc = "unknown" } print("touchesBegan on DebugView – touch type: \(typeDesc), location: \(t.location(in: self))") } } }
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
34
Apr ’25