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

USB Accessory Device Charging Behavior Changed with iOS18
Hello, We are experiencing some issues with our USB accessory unexpectedly charging the iOS device it is connected with only when the iOS device supports USB-C and is on iOS 18+ The following is a description of the discrepancy we note between iOS versions: After performing a USB Role switch, our Accessory becomes a typical USB Device and the Apple device becomes the USB host. with iOS 17: 
 The Accessory then sends a PowerSourceUpdate message to the iOS 17 device via iAP2 protocol. Apple device has a USB Type C Connector. * We are specifying: AvailableCurrentForDevice = 0 mA  DeviceBatteryShouldChargeIfPowerIsPresent = 1. Three observations: iPad Battery Settings page -  we observe  'Last charged to…' (indicating no charging) On the Lumify App running (iOS 17), we observe that UIKit.current.batteryState indicated 'Not charging' Battery icon on top right of the screen indicates 'No Charging' with iOS 18: The same Accessory sends the same PowerSourceUpdate message to the iOS 18 device via iAP2 protocol using USB Type C Connector. We are specifying the same: AvailableCurrentForDevice = 0 mA DeviceBatteryShouldChargeIfPowerIsPresent = 1. We observe: iPad Battery Settings page -  we observe  'Charging'  On the Lumify App running (iOS 18), we observe that UIKit.current.batteryState indicated 'Charging' Battery icon on top right of the screen indicates 'No Charging' Please could you help us understand why the Battery status is showing as 'Charging' in the Settings page and with the 'UIKit.current.batteryState' even though we have specified 'AvailableCurrentForDevice = 0 mA'?
 Since our accessory is heavily reliant on the Battery status / Charging state, is there potentially another way we get an accurate battery charging status that we are missing? Or are there other suggestions outside of what we do currently to ensure our accessory does not place the iOS18 device into a charging state?
5
0
409
May ’25
Animation Issue: SwiftUI View Not Animating Height Changes in UIHostingController
Hello, I’m developing an app where I display a SwiftUI view inside a UIHostingController embedded within a UIKit ViewController. I’m trying to animate the height of the UIHostingController’s view based on a switch’s value, but the SwiftUI view doesn’t animate at all. Below is a simplified version of my code: class ViewController: UIViewController { private lazy var parentView: UIView = { let view = UIView() view.backgroundColor = .red view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var hostingView: UIView = { let testView = TestView() let hostingController = UIHostingController(rootView: testView) let view = hostingController.view! view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var button: UISwitch = { let button = UISwitch() button.addTarget(self, action: #selector(onClickSwitch(sender:)), for: .valueChanged) button.translatesAutoresizingMaskIntoConstraints = false return button }() private var hostingViewHeightConstraint: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() view.addSubview(parentView) parentView.addSubview(hostingView) parentView.addSubview(button) NSLayoutConstraint.activate([ parentView.topAnchor.constraint(equalTo: view.topAnchor), parentView.bottomAnchor.constraint(equalTo: view.bottomAnchor), parentView.leadingAnchor.constraint(equalTo: view.leadingAnchor), parentView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) NSLayoutConstraint.activate([ hostingView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor), hostingView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor), hostingView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor) ]) hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: 0.5) hostingViewHeightConstraint?.isActive = true NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: parentView.centerXAnchor), NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: parentView, attribute: .centerY, multiplier: 0.25, constant: 0) ]) } @objc func onClickSwitch(sender: UISwitch) { hostingViewHeightConstraint?.isActive = false let multiplier: CGFloat = sender.isOn ? 0.25 : 0.5 hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: multiplier) hostingViewHeightConstraint?.isActive = true UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } } } I’m looking for the behavior demonstrated in the video below: Does anyone have suggestions on how to achieve this?
0
1
152
Mar ’25
How can I check applicationState by tap anps push cards?
when I implementation the UNUserNotificationCenterDelegate func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { var status = "" if (UIApplication.shared.applicationState == .active) { status = "active" } else if (UIApplication.shared.applicationState == .background) { status = "background" } else if (UIApplication.shared.applicationState == .inactive) { status = "inactive" } completionHandler() } I find that UIApplication.shared.applicationState == .background this case can not execute when application is in background。 why applicationState is inactive not background?
1
0
143
Mar ’25
How to Enable Group Navigation Behavior for Custom Views in VoiceOver?
In VoiceOver, when using Group Navigation style, the cursor first focuses on the semantic group. To navigate inside the group, a two-finger swipe (left or right) can be used. This behavior works for default containers like the Navigation Bar, Tab Bar, and Tool Bar. How can I achieve the same behavior for a custom view? I tried setting accessibilityContainerType = .semanticGroup, but it only works for Mac Catalyst. Is there an equivalent approach for iOS?
0
0
364
Mar ’25
Capturing self instead of using self. in switch case in DispatchQueue causes compiler error
I have an @objC used for notification. kTag is an Int constant, fieldBeingEdited is an Int variable. The following code fails at compilation with error: Command CompileSwift failed with a nonzero exit code if I capture self (I edited code, to have minimal case) @objc func keyboardDone(_ sender : UIButton) { DispatchQueue.main.async { [self] () -> Void in switch fieldBeingEdited { case kTag : break default : break } } } If I explicitly use self, it compiles, even with self captured: @objc func keyboardDone(_ sender : UIButton) { DispatchQueue.main.async { [self] () -> Void in switch fieldBeingEdited { // <<-- no need for self here case self.kTag : break // <<-- self here default : break } } } This compiles as well: @objc func keyboardDone(_ sender : UIButton) { DispatchQueue.main.async { () -> Void in switch self.fieldBeingEdited { // <<-- no need for self here case self.kTag : break // <<-- self here default : break } } } Is it a compiler bug or am I missing something ?
3
0
314
Jun ’25
SensorKit Data Not Retrieving
I have received permission from Apple to access SensorKit data for my app. I have granted all necessary permissions, but no data is being retrieved. The didCompleteFetch method is being called, but I’m unsure where to find event data like Device Usage and Ambient Light. Additionally, the didFetchResult method is never called. Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated. import SensorKit class ViewController: UIViewController, SRSensorReaderDelegate { let store = SRSensorReader(sensor: .deviceUsageReport) override func viewDidLoad() { super.viewDidLoad() requestSensorAuthorization() } func requestSensorAuthorization() { var sensors: Set<SRSensor> = [ .accelerometer, .deviceUsageReport, .messagesUsageReport, .visits, .keyboardMetrics, .phoneUsageReport, .ambientLightSensor ] if #available(iOS 16.4, *) { sensors.insert(.mediaEvents) } SRSensorReader.requestAuthorization(sensors: sensors) { error in if let error = error { print("Authorization failed: \(error.localizedDescription)") } else { self.store.startRecording() self.requestSensorData() print("Authorization granted for requested sensors.") } } } func requestSensorData() { let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().addingTimeInterval(-60 * 60).timeIntervalSinceReferenceDate) let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate) let request = SRFetchRequest() request.from = fromTime request.to = toTime request.device = SRDevice.current store.fetch(request) store.delegate = self } func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) { print("Fetch request completed: \(fetchRequest.from) to \(fetchRequest.to)") Task { do { let samples = try await reader.fetch(fetchRequest) print("Samples count: \(samples)") } catch { print("Error Fetching Data: \(error.localizedDescription)") } } } func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool { print(result) return true } }
0
0
151
Mar ’25
How to Ensure Data Privacy with VoiceOver Reading Sensitive Information?
VoiceOver reads out all visible content on the screen, which is essential for visually challenged users. However, this raises a privacy concern—what if a user accidentally focuses on sensitive information, like a bank account password, and it gets read aloud? How can developers prevent VoiceOver from exposing confidential data while still maintaining accessibility? Are there best practices or recommended approaches to handle such scenarios effectively?
1
0
302
Mar ’25
Best Way to Navigate to the Top Element Using VoiceOver
I’m currently focused on an element at the bottom of the screen. What is the proper way to quickly navigate to the top element? By default, there’s a four-finger single tap to move to the first element, but should I use the Rotor action instead to focus on the element I need? For example, in the Contacts app while adding a new contact, if I enter a value in a field at the bottom, there’s no quick way to directly save the contact. I have to manually navigate all the way to the top to tap the Done button, which feels a bit inconvenient. Is there a better way to handle this using VoiceOver?
2
0
293
Mar ’25
PHPickerViewController No Auto Focus
The issue is, I cannot auto acquire bluetooth keyboard focus in PHPickerViewController after enabling 'Full Keyboard Access' in my IPhone 14 with iOS version 18.3.1. The keyboard focus in PHPickerViewController will show, however, after I tapped on the blank space of the PHPickerViewController. How to make the focus on at the first place then? I'm using UINavigationController and calling setNavigationBarHidden(true, animated: false). Then I use this controller to present PHPickerViewController using some configuration setup below. self.configuration = PHPickerConfiguration() configuration.filter = .any(of: filters) configuration.selectionLimit = selectionLimit if #available(iOS 15.0, *), allowOrdering { configuration.selection = .ordered } configuration.preferredAssetRepresentationMode = .current Finally I set the delegate to PHPickerViewController and call UINavigationController.present(PHPickerViewController, animated: true) to render it. Also I notice animation showing in first video then disappear.
2
0
242
Mar ’25
ios18 crash reason: '*** -[__NSArrayM insertObjects:count:atIndex:]: attempt to insert nil object from objects[126976]'
Recently, my application has been receiving a lot of crashes every day, appearing on the iOS18 system. I can't find where the problem is and how can I solve it? Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Date/Time: 2025-03-10 14:55:49.541 +0800 OS Version: iOS 18.3.1 (22D72) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000 at 0x0000000000000000 Triggered by Thread: 1 Application Specific Information: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObjects:count:atIndex:]: attempt to insert nil object from objects[126976]' Thread 0: 0 libsystem_kernel.dylib 0x00000001e95c4788 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x00000001e95c7e98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x00000001e95c7db0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x00000001e95c7bfc mach_msg + 24 4 CoreFoundation 0x0000000197ee3804 0x197e6d000 + 485380 5 CoreFoundation 0x0000000197ee2eb0 0x197e6d000 + 482992 6 CoreFoundation 0x0000000197f35284 CFRunLoopRunSpecific + 588 7 GraphicsServices 0x00000001e51a14c0 GSEventRunModal + 164 8 UIKitCore 0x000000019aa7e674 0x19a690000 + 4122228 9 UIKitCore 0x000000019a6a4e88 UIApplicationMain + 340 10 MyApp 0x0000000102dbfd70 main + 104 11 (null) 0x00000001be18dde8 0x0 + 7484268008 Thread 1 name: com.apple.uikit.xpc-service Thread 1 Crashed: 0 CoreFoundation 0x0000000197e9a5fc 0x197e6d000 + 185852 1 libobjc.A.dylib 0x0000000195415244 objc_exception_throw + 88 2 CoreFoundation 0x0000000197ed46bc 0x197e6d000 + 423612 3 CoreFoundation 0x0000000197ed37b0 0x197e6d000 + 419760 4 CoreFoundation 0x0000000197e7f5f8 0x197e6d000 + 75256 5 MyApp 0x0000000103e4d4c0 startup_check_root + 12380 6 libdispatch.dylib 0x000000019fc2d248 0x19fc2b000 + 8776 7 libdispatch.dylib 0x000000019fc2efa8 0x19fc2b000 + 16296 8 libdispatch.dylib 0x000000019fc365cc 0x19fc2b000 + 46540 9 libdispatch.dylib 0x000000019fc37124 0x19fc2b000 + 49444 10 libdispatch.dylib 0x000000019fc4238c 0x19fc2b000 + 95116 11 libdispatch.dylib 0x000000019fc41bd8 0x19fc2b000 + 93144 12 libsystem_pthread.dylib 0x0000000222c04680 _pthread_wqthread + 288 13 libsystem_pthread.dylib 0x0000000222c02474 start_wqthread + 8
3
0
327
Mar ’25
Apple Intelligence + scrolling stuck
Hey, It seems that when Apple Intelligence is enabled, scrolling can become completely broken when using an app. This is affecting several apps, including telegram: https://github.com/TelegramMessenger/Telegram-iOS/issues/1570?reload=1 It seems that UIPanGesture is affected by this. (MapKit stop being able to scroll too). Killing + Relaunching the app fix the problem. Bug report ID, containing a video: FB16780431
2
1
178
Mar ’25
SwiftUI accessibility when embedded in UIKit
Hello, I struggle to do some UI testing using accessibility identifiers when I wrap some SwiftUI view using UIHostingController (our app is mainly coded using UIKit). Considering this SwiftUI view (simplified for this post): HStack { Text(self.title.uppercased()) .albusTheme(.header) .lineLimit(self.isMultiline ? nil : 1) .multilineTextAlignment(.leading) .accessibilityAddTraits(.isStaticText) .accessibilityIdentifier("section_title") } This view and its controller are embedded as a UITableViewHeaderFooterView in a UITableView. This is an extract of recursiveDescription output: | | | | | | <_UITableViewHeaderFooterContentView: 0x1076ad720; frame = (0 0; 393 40); layer = <CALayer: 0x6000006b1720>> | | | | | | | <_TtGC13ListComponent19SwiftUIFieldContentV20ListComponentLibrary17FormSectionHeader_: 0x1076ab980; baseClass = UIControl; frame = (0 0; 393 40); layer = <CALayer: 0x6000006b1da0>> | | | | | | | | <_TtGC7SwiftUI14_UIHostingViewV20ListComponentLibrary17FormSectionHeader_: 0x1078f9600; frame = (0 0; 393 40); gestureRecognizers = <NSArray: 0x600000e25d70>; backgroundColor = UIExtendedSRGBColorSpace 0.0666667 0.133333 0.227451 1; layer = <SwiftUI.UIHostingViewDebugLayer: 0x6000006b19a0>> | | | | | | | | | <_TtCOCV7SwiftUI11DisplayList11ViewUpdater8Platform13CGDrawingView: 0x106985550; frame = (16 12.6667; 147.667 14.6667); anchorPoint = (0, 0); opaque = NO; autoresizesSubviews = NO; layer = <_TtCOCV7SwiftUI11DisplayList11ViewUpdater8PlatformP33_65A81BD07F0108B0485D2E15DE104A7514CGDrawingLayer: 0x6000026b8240>> CGDrawingView seems to hide the underlying view hierarchy. Is there a way to access accessibility settings using the integration of SwiftUI in UIKit?
1
1
283
Mar ’25
Missing tab bar after switching tabs when tab bar is hidden in initial tab
Hi, I'm experiencing the behaviour outlined below. When I navigate programmatically on iPadOS or macOS from a tab that hides the tab bar to another tab, the tab bar remains hidden. The real app has it's entry point in UIKit (i.e. it uses an UITabBarController instead of a SwiftUI TabView) but since the problem is reproducible with a SwiftUI only app, I used one for the sake of simplicity. import SwiftUI @main struct HiddenTabBarTestApp: App { @State private var selectedIndex = 0 var body: some Scene { WindowGroup { TabView(selection: $selectedIndex) { Text("First Tab") .tabItem { Label("1", systemImage: "1.circle") } .tag(0) NavigationStack { Button("Go to first tab") { selectedIndex = 0 } .searchable(text: .constant("")) } .tabItem { Label("2", systemImage: "2.circle") } .tag(1) } } } } Reproduction: Create a new SwiftUI App with the iOS App template and use the code from above Run the app on iPadOS or macOS Navigate to the second tab Click into the search bar Click the "Go to first tab" button The tab bar is no longer visible Is this a bug in the Framework or is it the expected behaviour? If it's the expected behaviour, do you have a good solution/workaround that doesn't require me to end the search programmatically (e.g. by using @Environment(\.dismissSearch)) before navigating to another tab? The goal would be to show the tab bar in the first tab while keeping the search open in the second tab.
1
0
235
Mar ’25
iOS Screenshot prevention Whatsapp
It has been asked several times in the forum, but apple has always maintained that screenshot capture prevention is not supported, how is it that whatsapp and several financial apps are doing it, if screenshot capturing is not possible, its not DRM, is it the adding of a secured text as a layer on to the uiview layer? how have they designed a custom screen if that is the case? Also how is it getting approved by apple! If detection of airplay is possible and can be suppressed, why not screenshot?
2
0
506
Mar ’25
update UIKit view when viewDidLayoutSubviewsCallback from swiftUI wrapper gets call
Hello team i notice that we have a problem in our app that every time the user opens a Textfield the app freezes when the keyboard appears, this behavior was tracked down and it's a UI breaking design on a UIView [this view it's expandable and is original size is 80] [when it gets expanded 206.33] this is the view code I change the colors to easy check the other's views created inside private lazy var sharedUIPlaybackView: UIView = { let containerView = UIView().withAutoLayout() let propertySearchCriteria = PropertySearchCriteriaBuilder(hotelSearchParameters: viewModel.hotelSearchParameters).criteria var swiftUIView: SwiftUIView&lt;LodgingPlaybackWrapper&gt;! = nil swiftUIView = SwiftUIView( LodgingPlaybackWrapper(propertySearchCriteria: propertySearchCriteria, playbackUpdateNotificationSender: playbackUpdateNotificationSender, componentHandler: { [weak self] componentId in self?.componentReady(componentId) }), viewDidLayoutSubviewsCallback: { [weak self] in let extraPadding = self?.playbackViewExtraPadding ?? Spacing.spacing8x let newHeight = swiftUIView.frame.size.height + extraPadding // if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant { // self?.sharedUIPlaybackViewHeightConstraint?.constant = 206.33 // }else { // self?.sharedUIPlaybackViewHeightConstraint?.constant = 80 // } } ).withAutoLayout().withAccessibilityIdentifier("test") // sharedUIPlaybackViewHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0) // sharedUIPlaybackViewHeightConstraint?.isActive = true containerView.backgroundColor = .blue swiftUIView.backgroundColor = .red containerView.addSubview(swiftUIView) containerView.addConstraints([ swiftUIView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: playbackViewTopConstant), swiftUIView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Spacing.spacing4x), swiftUIView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Spacing.spacing4x), swiftUIView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -Spacing.spacing3x), swiftUIView.heightAnchor.constraint(equalToConstant: 206.33) ]) return containerView }() old devs created this function viewDidLayoutSubviewsCallback to connect user interaction on the wrapper and used on UIKit. this is the part where the math on the function gets weird and messed up the code by crashing the view viewDidLayoutSubviewsCallback: { [weak self] in let extraPadding = self?.playbackViewExtraPadding ?? Spacing.spacing8x let newHeight = swiftUIView.frame.size.height + extraPadding if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant { self?.sharedUIPlaybackViewHeightConstraint?.constant = newHeight } } ).withAutoLayout().withAccessibilityIdentifier("test") sharedUIPlaybackViewHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0) sharedUIPlaybackViewHeightConstraint?.isActive = true I commented this math because is crashing the app and instead of giving a dynamical height I placed as a constant constraint as default height this is how I solved the problem of the UI, but I still need to update the view each time the user clicks and gets call by the method viewDidLayoutSubviewsCallback what can I do? I tried to add like a conditional on the method if newHeight == 80 { containerView.addConstraints([ swiftUIView.heightAnchor.constraint(equalToConstant: 80.0) ]) containerView.layoutIfNeeded() } else { containerView.addConstraints([ swiftUIView.heightAnchor.constraint(equalToConstant: 206.33) ]) containerView.layoutIfNeeded() } like this but it didn't work [this is how it looks with the constant value of 206.33] [when it gets open looks good]
2
0
228
Mar ’25
How to Programmatically Simulate a Button Tap in SwiftUI?
In UIKit, certain events like a button tap can be simulated using: button.sendActions(for: .touchUpInside) This allows us to trigger the button’s action programmatically. However, in SwiftUI, there is no direct equivalent of sendActions(for:) for views like Button. What is the recommended approach to programmatically simulate a SwiftUI button tap and trigger its action? Is there an alternative mechanism to achieve this(and for other events under UIControl.event) , especially in scenarios where we want to test interactions or trigger actions without direct user input?
1
0
344
Mar ’25
Adjusting the width of a UISlider in self.navigationItem.titleView
I set the titleView of a view controller to a UISlider like so in viewDidLoad: UISlider *slider = [UISlider new]; self.navigationItem.titleView = slider; The desired outcome is that the slider takes the full width of the title view. This is working fine when the view is loaded in the wider landscape mode. The slider adjust its size as expected when rotating to portrait mode. However, when the view is loaded in the narrower portrait mode and then the device is rotated to landscape, the slider does not grow in width to make use of the newly available size. Why is that so and how can it get the desired outcome as described? After viewDidLoad: After rotating:
1
0
244
Mar ’25