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

UIKit Documentation

Post

Replies

Boosts

Views

Activity

"Save password" dialog blocks keyboard from appearing
When a VC dissapears that contained a textfiled with: textField.textContentType = .password I get the dialog "Would you like to save the password to iCloud keychain". If I send the app to background without dismissing the dialog first, and I get the app to foreground again, the dialog is not there but when I press any textfield inside the app the keyboard wont raise. Seems to be an iOS 13+ issue. Any help?
1
1
777
Feb ’24
Show overflow menu (more menu) as disabled in iOS 16+
Hi! I'm moving my UINavigationBar and UINavigationItem to the iOS 16 style and having trouble with disabling buttons. Before: I'm defining rightBarButtonItems with a few barButtonItems plus a (custom) menuButtonItem (which has a menu with some more actions). After: I'm defining trailingItemGroups and let the system create an overflow menu dynamically, depending on space. I'm also defining some additionalOverflowItems. Here's the problem: How can I access the button/barButtonItem that is showing the overflow menu and call isEnabled = false? My UI, so far, has disabled all buttons during edit mode. I don't want to hide them, but have them grayed out, including the overflow menu button. class MyVC : UIViewController { // ... override func setEditing(_ editing: Bool, animated: Bool) {         super.setEditing(editing, animated: animated) // ... // This doesn't disable the overflow menu button         navigationItem .trailingItemGroups .forEach { $0.barButtonItems .forEach { $0.isEnabled = !isEditing } }     } }
1
0
451
Feb ’24
Memory Leak Occurs When Setting prefersGrabberVisible Property on UISheetPresentationController
I've encountered a memory leak issue when setting the prefersGrabberVisible to true as shown below. There seems to be a bug where the view controller is not properly released from memory upon dismissal. if let sheet = presentedViewController.sheetPresentationController { sheet.detents = g_detents(defaultHeight: defaultHeight) sheet.prefersScrollingExpandsWhenScrolledToEdge = false sheet.prefersEdgeAttachedInCompactHeight = true sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = true sheet.prefersGrabberVisible = true // Commenting out this line prevents the memory leak sheet.selectedDetentIdentifier = .medium } present(presentedViewController, animated: true, completion: nil) Has anyone else experienced this issue, or does anyone have a workaround for this memory leak problem? Any insights or suggestions would be greatly appreciated.
0
1
318
Feb ’24
UITableView programmatically
struct SettingsList { var image: UIImage! var settingsName: String var settingsButton: String } class SettingsTableViewCell: UITableViewCell { static let reuseID = "note_cell" private lazy var settingImageView: UIImageView = { let view = UIImageView() return view }() private lazy var settingTitleLabel: UILabel = { let view = UILabel() view.font = UIFont.preferredFont(forTextStyle: .body) view.textColor = UIColor.label return view }() var button: UIButton = { let view = UIButton(type: .system) view.setImage(UIImage(named: "Chevron"), for: .normal) view.setTitle("Русский", for: .normal) view.setTitleColor(.secondaryLabel, for: .normal) view.tintColor = .black view.semanticContentAttribute = .forceRightToLeft view.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -15) return view }() var switchButton: UISwitch = { let view = UISwitch() return view }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = .secondarySystemBackground contentView.addSubview(settingImageView) contentView.addSubview(settingTitleLabel) contentView.addSubview(button) contentView.addSubview(switchButton) setupLayout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() settingImageView.image = nil settingTitleLabel.text = nil } func setup(title: String) { settingTitleLabel.text = title } func setup(image: UIImage) { settingImageView.image = image } private func setupLayout() { settingImageView.snp.makeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(contentView).offset(16) make.width.height.equalTo(24) } settingTitleLabel.snp.makeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(settingImageView.snp.trailing).offset(13) } button.snp.makeConstraints { make in make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).offset(-25) } switchButton.snp.makeConstraints { make in make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).offset(-25) } } } import UIKit class SettingsVC: UIViewController { private let settingsTableView = UITableView() let settingsList: [SettingsList] = [ SettingsList(image: UIImage(named: "language"), settingsName: "Язык", settingsButton: "chevron.right"), SettingsList(image: UIImage(named: "moon"), settingsName: "Темная тема", settingsButton: "switch.2"), SettingsList(image: UIImage(named: "trash"), settingsName: "Очистить данные", settingsButton: "") ] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground setupUI() } private func setupUI(){ setupNavigationItem() settingsTableView.register(SettingsTableViewCell.self, forCellReuseIdentifier: SettingsTableViewCell.reuseID) } private func setupNavigationItem() { navigationItem.title = "Settings" let image = UIImage(named: "settings") let resizedImage = image?.resized(to: CGSize(width: 25, height: 25)) let rightBarButtonItem = UIBarButtonItem(image: resizedImage, style: .plain, target: self, action: #selector(settingsButtonTapped)) rightBarButtonItem.tintColor = .black navigationItem.rightBarButtonItem = rightBarButtonItem } @objc func settingsButtonTapped(_ sender: UIButton){ } } extension SettingsVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { settingsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.reuseID, for: indexPath) as! SettingsTableViewCell print("Configuring cell for row \(indexPath.row)") if indexPath.row == 0 { cell.contentView.addSubview(cell.button) } else { cell.button.removeFromSuperview() } if indexPath.row == 1 { cell.contentView.addSubview(cell.switchButton) } else { cell.switchButton.removeFromSuperview() } cell.setup(title: settingsList[indexPath.row].settingsName) cell.setup(image: settingsList[indexPath.row].image) return cell } } It doesn't work when I click on this page(Settings.VC), It gives an error Thread 1: breakpoint 1.1 4.1 (1) and I don't know how to fix this;((( What I want to develop is this one:
0
0
253
Mar ’24
Is there a way to retrieve multiple files (files-urls) through the iOS share sheet (Activity View) without using the iOS share extension?
I wanted to implement a feature that allows the sharing of multiple files simultaneously to my app from an external app like Files. In my ApplicationDelegate file, I provided the following method, which currently only retrieves a single file URL from the share sheet, even when multiple files were selected in the Files app: - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { return [self handleSharedURL:url options:options]; } I'm curious to know if there is a way to obtain multiple file URLs without relying on a share extension. Any advice would be greatly appreciated.
0
0
325
Mar ’24
Is there a way to retrieve multiple files (files-urls) through the iOS share sheet (Activity View) without using the iOS share extension?
I wanted to implement a feature that allows the sharing of multiple files simultaneously to my app from an external app like Files. In my ApplicationDelegate file, I provided the following method, which currently only retrieves a single file URL from the share sheet, even when multiple files were selected in the Files app: - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { return [self handleSharedURL:url options:options]; } I'm curious to know if there is a way to obtain multiple file URLs without relying on a share extension. Any advice would be greatly appreciated.
0
0
376
Mar ’24
Disable AutoFill option in UITextField or have control over the text which is being pasted using that option.
I have form fields in an app, I have some validations to perform like phone number should only have digits and not alphabets, however when user uses AutoFill option doing long press on textfield they have option to choose Contacts and they can tap on name and it will paste alphabets in my Phone number field, that behavior I don't want as my validations will not be fulfilled. There are no callbacks to detect and prevent that text from being pasted. In shouldChangeCharactersIn delegate method even if I return false for that paste event it ignores that and forcefully it gets pasted. Please help how to tackle such scenarios to perform above mentioned validations. Thanks
2
2
1.5k
Mar ’24
How do I inject reference types in a table view cell and reload the row of the said cell without causing a memory leak?
For instance, executing the following code, in which a stepper is injected in a table view cell and the cell is reloaded when the user changes the stepper's value, causes the memory usage to grow pretty quickly (I stopped the simulation at 1GB) when you tap on the stepper. Also the CPU usage jumps straight at 99%, and the UI freezes. Note: I'd like to know exactly what I asked, not how to make a table view cell with a stepper in general. I know that calling reloadData() or reconfigureRows(at:) doesn't cause any of the mentioned issues. Also please don't reply with questions like "Have you tried to use weak references?". The code is short: please reply with a working solution if you can. class ViewController: UIViewController { let tableView = UITableView() let stepper = UIStepper() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.dataSource = self stepper.addTarget(self, action: #selector(stepperValueChanged), for: .valueChanged) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = view.bounds } @objc private func stepperValueChanged() { tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.accessoryView = stepper var configuration = cell.defaultContentConfiguration() configuration.text = "\(stepper.value)" cell.contentConfiguration = configuration return cell } }
2
0
427
Mar ’24
UIKit Collection View inside TableViewCell
I have a collelctionview inside a tableview cell in UIKit. The cells of the collectionview have dynamic content and their height and width depends on the content, which decides the height of the collectionview inside tableview cell. I have used many methods to calculate height correctly at first and as I scroll the tableview or perform any button action, the height does not gets correctly to me. Please provide a good solution or replacement for this problem.
0
0
594
Mar ’24
UITextView selectedRange property
What is the string representation (or another object) for this property is applied? Can we use Range(txtView.selectedRange, in: txtView.text) to get valid indices in UITextView.text? What is the difference of UITextView.selectedRange to UITextView.SelectedTextRange?
1
0
425
Mar ’24
UICollectionView _updateLayoutAttributesForExistingVisibleViewsFadingForBoundsChange
The crash history shown in Xcode shows a lot of crash highlighted at UICollectionView _updateLayoutAttributesForExistingVisibleViewsFadingForBoundsChange The stack trace shows now application code directly involved, there is even no hint found regarding UICollectionView _updateLayoutAttributesForExistingVisibleViewsFadingForBoundsChange. After this call an assertionHandler triggers. Has anyone seen this or a hint what causes this crash? Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Terminating Process: app [2425] Triggered by Thread: 0 Last Exception Backtrace: 0 CoreFoundation 0x1a3f3eb28 __exceptionPreprocess + 164 (NSException.m:249) 1 libobjc.A.dylib 0x19bd92f78 objc_exception_throw + 60 (objc-exception.mm:356) 2 Foundation 0x1a33a3920 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 188 (NSException.m:252) 3 UIKitCore 0x1a614a464 -[UICollectionView _updateLayoutAttributesForExistingVisibleViewsFadingForBoundsChange:] + 1992 (UICollectionView.m:0) 4 UIKitCore 0x1a6149858 -[UICollectionView _updateVisibleCellsNow:] + 3132 (UICollectionView.m:5688) 5 UIKitCore 0x1a6148b2c -[UICollectionView layoutSubviews] + 304 (UICollectionView.m:6953) 6 UIKitCore 0x1a61010f8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1528 (UIView.m:20041) 7 QuartzCore 0x1a552be30 CA::Layer::layout_if_needed(CA::Transaction*) + 504 (CALayer.mm:10816) 8 QuartzCore 0x1a552b9b4 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148 (CALayer.mm:2598) 9 QuartzCore 0x1a5531bb4 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 464 (CAContextInternal.mm:2760) 10 QuartzCore 0x1a552b1bc CA::Transaction::commit() + 648 (CATransactionInternal.mm:432) 11 QuartzCore 0x1a552ae64 CA::Transaction::flush_as_runloop_observer(bool) + 88 (CATransactionInternal.mm:942) 12 UIKitCore 0x1a6179260 _UIApplicationFlushCATransaction + 52 (UIApplication.m:3160) 13 UIKitCore 0x1a6178d78 _UIUpdateSequenceRun + 84 (_UIUpdateSequence.mm:119) 14 UIKitCore 0x1a6178468 schedulerStepScheduledMainSection + 144 (_UIUpdateScheduler.m:1037) 15 UIKitCore 0x1a6178524 runloopSourceCallback + 92 (_UIUpdateScheduler.m:1186) 16 CoreFoundation 0x1a3e8962c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1957) 17 CoreFoundation 0x1a3e888a8 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001) 18 CoreFoundation 0x1a3e87058 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2038) 19 CoreFoundation 0x1a3e85d88 __CFRunLoopRun + 828 (CFRunLoop.c:2955) 20 CoreFoundation 0x1a3e85968 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 21 GraphicsServices 0x1e81834e0 GSEventRunModal + 164 (GSEvent.c:2196) 22 UIKitCore 0x1a62f8edc -[UIApplication _run] + 888 (UIApplication.m:3692) 23 UIKitCore 0x1a62f8518 UIApplicationMain + 340 (UIApplication.m:5282) 24 app 0x1028edf68 main + 176 (main.swift:5) 25 dyld 0x1c73a7d84 start + 2240 (dyldMain.cpp:1298) Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
1
1
309
Mar ’24
SwiftUI Bug in Voice Over when app language is French
My app language is set to French. If my device language is set to French, I do not see this issue. If my device language is set to English, In the app, voice over reads all UIKit views with female voice (French accent), and all SwiftUI view with male voice (French accent). Is this a bug with SwiftUI or UIKit ? I would expect the gender voice should not be changed irrespective of UIKit/SwiftUI views. I tried many ways, but none fixed the issues. I am not sure what is causing this or how to fix this. Our app is majorly built in UIKit and we started to use SwiftUI views for small views, and if this accessibility issues continue, we would like to stop using SwiftUI. Some of the ways I tried are: Set the locale of swiftUI view .environment(\.locale, "fr-CA") I could not find anything in the documentation that could address this.
1
1
543
Mar ’24
UIFontPickerViewController screen font is broken or black screen issue
We are working on a screen that registers fonts using UIFontPickerViewController. Sometimes when I run UIFontPickerViewController I just get a black screen. Or, the font of the UI inside UIFontPickerViewController is broken and displayed as strange special characters. When displayed as a special character, screen scrolling becomes slow and the font is not displayed in the list when scrolling down. When this happens, the Xcode debug window shows “error received: connection invalidated.” This error message is displayed. This happened to me often while developing UIFontPickerViewController . Could you please advise how to resolve this issue? Or, I hope Apple resolves the issue quickly and updates. The development device where the issue occurs is iPhone SE3 iOS 17.4.
4
0
818
Mar ’24
"UIDevice.current.batteryLevel" is always "0" in macOS Sonoma 14.4
I recently updated to macOS Sonoma 14.4 and now UIDevice.current.batteryLevel is always 0. Code to reproduce: import SwiftUI struct ContentView: View { @State private var monitoringEnabled = UIDevice.current.isBatteryMonitoringEnabled; @State private var batteryLevel = UIDevice.current.batteryLevel; var body: some View { VStack { Text("Battery Monitoring Enabled: " + String(monitoringEnabled)) Text("Battery Level: " + String(batteryLevel)) Button("Toggle Monitoring") { monitoringEnabled = !monitoringEnabled; UIDevice.current.isBatteryMonitoringEnabled = monitoringEnabled; batteryLevel = UIDevice.current.batteryLevel; } } .padding() } } Run the above on a macOS 14.4 target, click "Toggle Monitoring", and you'll see battery level is reported as 0: I also see the following error in my app logs when running on macOS 14.4: Error retrieving battery status: result=-536870207 percent=0 hasExternalConnected=1 isCharging=0 isFullyCharged=0 This code displays the expected battery level when running on an actual iOS device:
3
3
1.2k
Mar ’24
iOS size classes like Regular, compact, Any
I am new to using iOS Objective-C size classes like Regular, compact, Any. I found that Compact size classes are anything less than ~640 pts and Regular size classes are anything larger than ~640 pts . Is that correct for both iphone and ipad? How can I use size class to make an image full screen on all the iphone and ipad devices and on any orientation? How many images will I need? Any help and insight is greatly appreciated!
0
0
853
Mar ’24
How to change view background color from other tableView?
Hi there In themeTableView override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath.section == 0 && indexPath.row == 0) { HappyView().view.backgroundColor = UIColor.systemBlue } if (indexPath.section == 0 && indexPath.row == 1) { HappyView().view.backgroundColor = UIColor.systemGreen } } But the HappyView background color didn't change after I selected the cell and navigated to the HappView.
1
0
354
Mar ’24
UIPrintPanelNavigationController crash when tapping print option. in share sheet
I am presenting a UIActivityViewController controller on button tap with print option in the UIActivityViewController. My app only supports portrait mode. when i tap the print option app crashes with following error. *** Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and [UIPrintPanelNavigationController shouldAutorotate] is returning YES' *** First throw call stack:
0
0
227
Mar ’24
SwiftUI NavigationBar using UIHostingController does not Display correctly until NSLayoutConstraint is broken
I'm facing an issue where the navigation bar title of a SwiftUI view does not display correctly on the first render. It only appears correctly after switching to another tab and then coming back. Alongside this issue, I'm receiving the following constraint error in the console: `[UIKitCore] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x6000021d2a30 h=-&- v=--& Test.minY == 0 (active, names: Test:0x11560c7c0, '|':UILayoutContainerView:0x11560e180 )>", "<NSAutoresizingMaskLayoutConstraint:0x6000021d08c0 h=-&- v=--& Test.height == 96 (active, names: Test:0x11560c7c0 )>", "<NSLayoutConstraint:0x6000021d70c0 V:[Test]-(0)-[UIFocusContainerGuide:0x600003deab20'UINavigationControllerContentFocusContainerGuide'] (active, names: Test:0x11560c7c0 )>", "<NSLayoutConstraint:0x6000021d61c0 UIFocusContainerGuide:0x600003deab20'UINavigationControllerContentFocusContainerGuide'.bottom == UILayoutContainerView:0x11560e180.bottom (active)>", "<NSLayoutConstraint:0x6000021c6bc0 'UIView-Encapsulated-Layout-Height' UILayoutContainerView:0x11560e180.height == 0 (active)>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x6000021d70c0 V:[Test]-(0)-[UIFocusContainerGuide:0x600003deab20'UINavigationControllerContentFocusContainerGuide'] (active, names: Test:0x11560c7c0 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.` SwiftUI View struct ContentView: View { var body: some View { NavigationStack { ScrollView { VStack(spacing: 20) { ForEach(0..<10) { index in VStack { Text("Section \(index)").font(.headline).padding() ForEach(0..<5) { itemIndex in Text("Item \(itemIndex)").padding() } } .frame(maxWidth: .infinity) .background(Color.gray.opacity(0.2)) .cornerRadius(10) .padding(.horizontal) } } }.navigationTitle("Overview").navigationBarTitleDisplayMode(.automatic) } } } ExpoView extends ... extends UIView class ExpoContentView: ExpoView { required init(appContext: AppContext? = nil) { super.init(appContext: appContext) self.backgroundColor = .white // Init the view controller let contentView = ContentView() let hostingController = UIHostingController(rootView: contentView) setupHostingController(hostingController) func setupHostingController(_ hostingController: UIHostingController<some View>) { hostingController.view.translatesAutoresizingMaskIntoConstraints = false hostingController.view.backgroundColor = .clear addSubview(hostingController.view) NSLayoutConstraint.activate([ hostingController.view.topAnchor.constraint(equalTo: self.topAnchor), hostingController.view.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor), hostingController.view.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor), hostingController.view.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor) ]) } } How can I achieve that it is correctly shown at the first render?
0
0
699
Mar ’24