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

UIKit Documentation

Post

Replies

Boosts

Views

Activity

State Restoration: Deleting current state data
In the past, it seemed that if you used the app switcher and killed the app, that state restoration data would not persist, and starting the app again would not load any stored state data. But now (at lest in iOS 17) that is no longer the case. There are situations where the old state might cause issues, which we obviously need to fix, but users should be able to clear the state data. I am not using sessions and am using the older methods - application:shouldSaveApplicationState: and application:shouldRestoreApplicationState:. My question is, how can I tell my users to reset/clear state restoration data if needed?
0
0
16
1h
Can an automaker app and a Carplay app (when automaker is not possible) live in the same App?
Hi, I'm trying to investigate if there is any way to have an app that displays an automaker app when the Carplay environment has the automaker protocol string, and displays a Carplay App (Driving Task) when there isn't the automaker protocol string. I was able to start developing an automaker app, but with an iOS16.0 deprecated method (with UIScreen Notifications), I'm not able to do it via the scene delegate... There is any kind of documentation of how to do it? I think the clue may be in the scene delegate with the property Preferred Default Scene Session Role, where I think the automaker app is a Window Application Session Role, but the scene delegate is not triggered when I open the Carplay App in the simulator. So am I missing something? Is there a way to do it or have I to publish two apps in order to use the two kind of carplay apps... ? Thank you very much.
1
0
30
15h
iOS 18 beta - Cancelling Interactive UICollectionView Layout Transition causes the collectionView to disappear
On iOS18 beta1 & beta2 builds, calling collectionView.cancelInteractiveTransition() after a call to startInteractiveTransition(to:completion:) seems to remove the intermediate transition layout object from the collection view, but doesn't reinstalls the original layout, which results in the collection view disappearing completely. This was not the case in previous iOS versions, so maybe a beta bug? Possibly related, Xcode logs the following error in the console in the exact moment when the collectionView disappears: “Requesting visual style in an implementation that has disabled it, returning nil. Behavior of caller is undefined.” I filled a bug report, together with sample project, just in case FB14057335 Thanks!
0
0
44
7h
How to display "Return to app" option in the "Return to Clock" watch menu?
I have a sports iOS app with a paired watch app, that uses location to update some UI elements. I technically need the location only when the watch app is in foreground, but since another requirement is to stop the clock from replacing the app, I decided to add background location checks. I followed the steps from the documentation (adding Background Modes to the watch extension target, setting allowsBackgroundLocationUpdates to true): the location update works fine when I go to the clock, the app's icon is displayed in a circle at the top (bringing the app back to foreground on tap). The only problem is that the "Return to app" option in the "Return to Clock" settings menu is missing, what do I need to do in order to display it? Here's an example of what it looks like for the Strava app: and how it looks for mine.
1
0
212
2w
UIGraphicsImageRenderer memory issue (iOS 17.5.1)
Testing on iPhone 12 mini, I have encountered a weird situation. I am try to take snapshot of my view, which works fine but the memory is never released after the snapshot is taken. func screenshot(view: UIView, scale:Double) -> URL? { guard let containerView = view.superview, let containerSuperview = containerView.superview else { return nil } let rendererFormat = UIGraphicsImageRendererFormat() rendererFormat.scale = scale var renderer = UIGraphicsImageRenderer(bounds: containerView.frame, format: rendererFormat) let image = autoreleasepool { return renderer.image { context in containerSuperview.drawHierarchy(in: containerSuperview.layer.frame, afterScreenUpdates: true) //memory hog starts from here } } guard let data = image.heicData() else { return nil } //more code to save data to file URL and return it } initially it appears to work normally but as soon as I change the scale: rendererFormat.scale = 10 I can see a spike in memory but the problem is then the memory is never released even after the image is saved. so initially, the app uses: 35MB memory -> when processing the memory usage jumps to expected 250MB to 300MB to process large image -> after processing the memory goes down to around 90MB to 120MB but it never really returns to it's original 35MB state. Is this a bug or this is expected? If this is expected behaviour then is there any low level API to free the memory after it's job is done.
1
0
82
2d
Implementing Undo/Redo Feature in UITextView with IME Support
Currently, we are implementing an undo/redo feature in UITextView. However, we cannot use the built-in UndoManager in UITextView because we have multiple UITextView instances inside a UICollectionView. Since UICollectionView recycles UITextView instances, the same UITextView might be reused in different rows, making the built-in UndoManager unreliable. The shouldChangeTextIn method in UITextViewDelegate is key to implementing undo/redo functionality properly. Here is an example of our implementation: extension ChecklistCell: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { // Get the current text let s = textView.text ?? "" // Get the starting position of the change let start = range.location // Get the number of characters that will be replaced let count = range.length // Get the number of characters that will be added let after = text.count print(">>>> The current text = \"\(s)\"") print(">>>> The starting position of the change = \(start)") print(">>>> The number of characters that will be replaced = \(count)") print(">>>> The number of characters that will be added = \(after)") print(">>>>") if let delegate = delegate, let checklistId = checklistId, let index = delegate.checklistIdToIndex(checklistId) { delegate.attachTextAction(s: s, start: start, count: count, after: after, index: index) } return true } } Working scene behind the UITextViewDelegate However, this implementation does not work well with non-English input using an IME. When using an IME, there is an intermediate input before the final input is produced. For example, typing "wo" (intermediate input) produces "我" (final input). Currently, UITextViewDelegate captures both "wo" and "我". UITextViewDelegate captures both "wo" and "我" Is there a way to ignore the intermediate input from IME and only consider the final input? In Android, we use the beforeTextChanged method in TextWatcher to seamlessly ignore the intermediate input from IME and only consider the final input. You can see this in action in this Android captures only "我" Is there an equivalent way in iOS to ignore the intermediate input from IME and only take the final input into consideration?
0
0
47
14h
UICollectionView scrolls back to 0 using comp layout
PLATFORM AND VERSION: iOS Development environment: Xcode 15.2 macOS 13.6.3 iOS 17.2 DESCRIPTION OF PROBLEM Using a UICollectionView with compositional layout, once the view is created, programmatically scroll to a row using the scrollToItem method. For this report I created a simple dataSource with 400 rows and 1 section. Scrolling to row 200 in viewDidLoad or viewWillAppear after calling collectionView.layoutIfNeeded(). The compositional layout's orthogonalScrollingBehavior is set to .groupPagingCentered The collectionView behaves as expected and shows row 200. Issue The issue is that when swiping too quickly to go to row 199 or prior the entire collectionView is reset to row 0. This does not happen when swiping to go on row 201 or above. STEPS TO REPRODUCE Run the app on iPhone. Swipe right quickly (to go to row prior to 200) Expected result: row 199 or 198 is shown Actual result: collectionView is reset to row 0
2
0
86
4d
uncaught exception 'NSInternalInconsistencyException', reason: 'Layout requested for visible navigation bar.
Hey,bros: I meet this crash,but I can't find any useful infos to fix this crash.And this crash only happens on iOS17. Here are the crash infos: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Layout requested for visible navigation bar, <UINavigationBar: 0x106128820; frame = (0 0; 430 44); opaque = NO; autoresize = W; tintColor = UIExtendedGrayColorSpace. Here are the stacks: Thread 0 name: com.apple.main-thread CoreFoundation ___exceptionPreprocess (in CoreFoundation) libobjc.A.dylib _objc_exception_throw (in libobjc.A.dylib) Foundation -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] (in Foundation) UIKitCore -[UINavigationBar layoutSubviews] (in UIKitCore) UIKitCore -[UIView(CALayerDelegate) layoutSublayersOfLayer:] (in UIKitCore) longbridge-ios-app -[UIView(Thread) ex_layoutSublayersOfLayer:] (in longbridge-ios-app:UIView+Thread.m:36) UIKitCore -[UINavigationBar layoutSublayersOfLayer:] (in UIKitCore) QuartzCore CA::Layer::layout_if_needed(CA::Transaction*) (in QuartzCore) UIKitCore -[UIView(Hierarchy) layoutBelowIfNeeded] (in UIKitCore) UIKitCore -[UINavigationController _positionNavigationBarHidden:edge:initialOffset:] (in UIKitCore) UIKitCore -[UINavigationController _positionNavigationBarHidden:edge:] (in UIKitCore) UIKitCore -[UINavigationController _updateBarsForCurrentInterfaceOrientationAndForceBarLayout:] (in UIKitCore) UIKitCore -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:] (in UIKitCore) UIKitCore -[UINavigationController viewDidMoveToWindow:shouldAppearOrDisappear:] (in UIKitCore) UIKitCore -[UIView(Internal) _didMoveFromWindow:toWindow:] (in UIKitCore) UIKitCore ___45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke (in UIKitCore) CoreAutoLayout -[NSISEngine withBehaviors:performModifications:] (in CoreAutoLayout) UIKitCore -[UIView _postMovedFromSuperview:] (in UIKitCore) UIKitCore -[UIView(Internal) _addSubview:positioned:relativeTo:] (in UIKitCore) UIKitCore -[UITransitionView transition:fromView:toView:removeFromView:] (in UIKitCore) UIKitCore -[UIViewControllerBuiltinTransitionViewAnimator animateTransition:] (in UIKitCore) UIKitCore ____UIViewControllerTransitioningRunCustomTransition_block_invoke_3 (in UIKitCore) UIKitCore +[UIKeyboardSceneDelegate _pinInputViewsForKeyboardSceneDelegate:onBehalfOfResponder:duringBlock:] (in UIKitCore) UIKitCore ____UIViewControllerTransitioningRunCustomTransition_block_invoke_2 (in UIKitCore) UIKitCore +[UIView(Animation) _setAlongsideAnimations:toRunByEndOfBlock:] (in UIKitCore) UIKitCore __UIViewControllerTransitioningRunCustomTransition (in UIKitCore) UIKitCore ___56-[UIPresentationController runTransitionForCurrentState]_block_invoke_3 (in UIKitCore) UIKitCore -[_UIAfterCACommitBlock run] (in UIKitCore) UIKitCore -[_UIAfterCACommitQueue flush] (in UIKitCore) UIKitCore __runAfterCACommitDeferredBlocks (in UIKitCore) UIKitCore __cleanUpAfterCAFlushAndRunDeferredBlocks (in UIKitCore) UIKitCore __UIApplicationFlushCATransaction (in UIKitCore) UIKitCore __UIUpdateSequenceRun (in UIKitCore) UIKitCore _schedulerStepScheduledMainSection (in UIKitCore) UIKitCore _runloopSourceCallback (in UIKitCore) CoreFoundation _CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION (in CoreFoundation) CoreFoundation ___CFRunLoopDoSource0 (in CoreFoundation) CoreFoundation ___CFRunLoopDoSources0 (in CoreFoundation) CoreFoundation ___CFRunLoopRun (in CoreFoundation) CoreFoundation _CFRunLoopRunSpecific (in CoreFoundation) GraphicsServices _GSEventRunModal (in GraphicsServices) UIKitCore -[UIApplication _run] (in UIKitCore) UIKitCore _UIApplicationMain (in UIKitCore) longbridge-ios-app main (in longbridge-ios-app:main.m:22) dyld start (in dyld)
1
0
57
5d
View appears transparent over tableView, whatever alpha channel
I have a view in storyboard, with a tableView and a coloured UIView. The UIView is declared after tableView, so it appears on top of tableView. However, it appears semi transparent over the tableView. In addition, I cannot set its alpha channel to values other than 1 or 0 (e.g., 0.9) But if I create the view programmatically, the view if fully opaque as expected. What am I missing ?
1
0
519
Dec ’23
View with 2 labels of dynamic height
Hello, I try to do the same as the UIListContentConfiguration. Because I want to have a UITableViewCell with an image at beginning, then 2 Labels and an image at the end (accessoryView/Type should also be usable). I also want to have the dynamic behavior of the two labels, that if one or both of them exceeds a limit, that they are put under each under. But I cannot use the UIListContentConfiguration.valueCell, because of the extra image at the end. So I have tried to make a TextWrapper as an UIView, which contains only the two UILabels and the TextWrapper should take care of the dynamic height of the UILabels and put them side to side or under each other. But here in this post Im only concentrating on the issue with the labels under each other, because I have managed it to get it working, that I have two sets of Constraints and switch the activeStatus of the constraints, depending on the size of the two labels. But currently only the thing with the labels under each under makes problems. Following approaches I have tried for the TextWrapper: Using only constraints in this Wrapper (results in ambiguous constraints) Used combinations of constraints + intrinsicContentSize (failed because it seems that invalidateIntrinsicContentSize doesn't work for me) Approach with constraints only Following code snippet results in ambiguous vertical position and height. Because I have 3 constraints (those with the defaultHigh priorities). class TextWrapper: UIView { let textLabel = UILabel() let detailLabel = UILabel() init() { super.init(frame: .zero) self.addSubview(self.textLabel) self.addSubview(self.detailLabel) self.textLabel.numberOfLines = 0 self.detailLabel.numberOfLines = 0 self.directionalLayoutMargins = .init(top: 8, leading: 16, bottom: 8, trailing: 8) self.translatesAutoresizingMaskIntoConstraints = false self.textLabel.translatesAutoresizingMaskIntoConstraints = false self.detailLabel.translatesAutoresizingMaskIntoConstraints = false // Content Size self.textLabel.setContentCompressionResistancePriority(.required, for: .vertical) self.detailLabel.setContentCompressionResistancePriority(.required, for: .vertical) // Constraints self.textLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true self.textLabel.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).constraint(with: .defaultHigh) self.textLabel.widthAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.widthAnchor).isActive = true self.detailLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true self.detailLabel.topAnchor.constraint(equalTo: self.textLabel.bottomAnchor, constant: 2).constraint(with: .defaultHigh) self.detailLabel.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).constraint(with: .defaultHigh) self.detailLabel.widthAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.widthAnchor).isActive = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } Approach with intrinsicContentSize Pretty similar to the above, with only difference that I invalidate the intrinsicContentSize in the layoutSubviews, because at the first call of the intrinsicContentSize the width of the View is zero. I also tried different things like setNeedsLayout with layoutIfNeeded but nothing really works. After I invalidate the intrinsicContentSize in the layoutSubviews the intrinsicContentSize is called with the correct width of the View and calculates the correct height, but the TableView doesn't update the height accordingly. class TextWrapper: UIView { let textLabel = UILabel() let detailLabel = UILabel() init() { super.init(frame: .zero) self.addSubview(self.textLabel) self.addSubview(self.detailLabel) self.textLabel.numberOfLines = 0 self.detailLabel.numberOfLines = 0 self.directionalLayoutMargins = .init(top: 8, leading: 16, bottom: 8, trailing: 8) self.translatesAutoresizingMaskIntoConstraints = false self.textLabel.translatesAutoresizingMaskIntoConstraints = false self.detailLabel.translatesAutoresizingMaskIntoConstraints = false // Content Size self.textLabel.setContentCompressionResistancePriority(.required, for: .vertical) self.detailLabel.setContentCompressionResistancePriority(.required, for: .vertical) // Constraints self.textLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true self.textLabel.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).constraint(with: .defaultHigh) self.textLabel.widthAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.widthAnchor).isActive = true self.detailLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true self.detailLabel.topAnchor.constraint(equalTo: self.textLabel.bottomAnchor, constant: 2).constraint(with: .defaultHigh) self.detailLabel.widthAnchor.constraint(lessThanOrEqualTo: self.layoutMarginsGuide.widthAnchor).isActive = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { let maxLabelWidth = self.bounds.width guard maxLabelWidth > 0 else { // The first time it has a width of 0, so we are giving a default height in this case, to dont produce a error in TableView return CGSize(width: UIView.noIntrinsicMetric, height: 44) } let textLabelSize = self.textLabel.sizeThatFits(CGSize(width: maxLabelWidth, height: .greatestFiniteMagnitude)) let detailLabelSize = self.detailLabel.sizeThatFits(CGSize(width: maxLabelWidth, height: .greatestFiniteMagnitude)) let totalHeight = textLabelSize.height + detailLabelSize.height + 16 return CGSize(width: UIView.noIntrinsicMetric, height: totalHeight) } override func layoutSubviews() { super.layoutSubviews() self.invalidateIntrinsicContentSize() } I also tried to use the intrinsicContentSize with only layoutSubviews, but this haven't worked also. Does anybody have ran into such issues? And know how to fix that?
2
0
65
3d
UICollectionViewDiffableDataSource deadlock scenario on iOS 18
We encountered a deadlock scenario when our app runs on iOS 18. It happens when we use the async version of UICollectionViewDiffableDataSource.apply() and request a section snapshot from within the UICollectionViewCompositionalLayoutSectionProvider. The deadlock doesn't happen when using the completion handler version of UICollectionViewDiffableDataSource.apply() or when requesting a full snapshot from the data source. On iOS 17 there is no issue. import UIKit class ViewController: UICollectionViewController { private enum SectionIdentifier: Hashable { case test } private enum ItemIdentifier: Hashable { case test(UUID) } private typealias Snapshot = NSDiffableDataSourceSnapshot<SectionIdentifier, ItemIdentifier> private typealias SectionSnapshot = NSDiffableDataSourceSectionSnapshot<ItemIdentifier> private typealias DataSource = UICollectionViewDiffableDataSource<SectionIdentifier, ItemIdentifier> private lazy var dataSource: DataSource = { let cellRegistration = UICollectionView.CellRegistration<UICollectionViewCell, UIColor> { cell, _, color in cell.contentView.backgroundColor = color } return DataSource(collectionView: collectionView) { [weak self] collectionView, indexPath, itemIdentifier in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: .red) } }() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = dataSource collectionView.collectionViewLayout = UICollectionViewCompositionalLayout { [weak self] section, environment -> NSCollectionLayoutSection? in // calling `UICollectionViewDiffableDataSource.snapshot(for:)` from the `UICollectionViewCompositionalLayoutSectionProvider` leads to deadlock on iOS 18 let numberOfItems = self?.dataSource.snapshot(for: .test).items.count ?? 0 // deadlock // calling `UICollectionViewDiffableDataSource.snapshot()` causes no issue // let numberOfItems = self?.dataSource.snapshot().numberOfItems(inSection: .test) ?? 0 // works let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .absolute(100), heightDimension: .absolute(100))) let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(100)), repeatingSubitem: item, count: numberOfItems) group.interItemSpacing = .fixed(5) return .init(group: group) } var snapshot = Snapshot() snapshot.appendSections([.test]) snapshot.appendItems([.test(UUID()), .test(UUID()), .test(UUID()), .test(UUID())]) // using the async wrapper `UICollectionViewDiffableDataSource.apply()` on any thread leads to deadlock on iOS 18 Task { await dataSource.apply(snapshot) } // deadlock // Task { @MainActor in await dataSource.apply(snapshot) } // deadlock // using `UICollectionViewDiffableDataSource.apply()` with completion handling causes no issue // Task { dataSource.apply(snapshot) } // works // dataSource.apply(snapshot) // works } } Full example project at https://github.com/antiraum/iOS18_UICollectionViewDiffableDataSource_deadlock
2
0
132
1w
UIAlertController no longer appears as a popover in macOS Sonoma
Prior to macOS 14, a Catalyst app could present a UIAlertController as a popover, just as you can on the iPad. While this still works on the iPad, the presentation on macOS now uses the same style as the iPhone. The UIAlertController's popoverPresentationController property is always nil, no matter how it is configured. Doe anyone know of a way to restore the prior behavior under Sonoma?
3
2
645
Oct ’23
Navigation bar not shown in Supplementary view of a UISplitView in macOS Sonoma
I've run into a problem that has been giving me fits for a while and have yet to be able to find a solution. We have a Catalyst app that uses a three-pane UISplitView. The middle and third panes show the navigation bar of the UINavigationController hosted in each pane. However, when building under Xcode 15, the navigation bar is not shown in the middle pane when running under macOS 14. It is shown, as expected, when the app is run under prior versions of macOS. It also appears as it should under macOS 14 if the app is built with Xcode 14. If you push another view controller onto the navigation controller's stack with the animate flag set to true, the navigation bar will appear. When you go back to the root controller, the navigation bar is present as it should be. However, if you push the controller with the animate flag set to false, the navigation bar does not appear. I've been able to reproduce this in an isolated test app with just the relevant components. The first screenshot at the end is from a test app that illustrates the problem. The second screenshot shows what it should look like (and does look like under macOS 13). It should be noted that UINavigationBar.appearance().preferredBehavioralStyle = .pad is set. If any Apple folk would kindly like to look into this, I created a feedback for it: FB13260893. The feedback entry has a sample app, screenshots, and even a screen recording demonstrating the problem. Has anyone else run into this or does anyone have any suggestions for a fix/workaround? Thanks, Kevin
2
1
445
Oct ’23
Change in title bar behavior in Catalyst app when building under Xcode 16
I'm running into a change in behavior with the title bar when building our Catalyst app under Xcode 16 versus what we are seeing with the same code built under Xcode 15. The title bar is hidden, as it should be in the Xcode 15 build. However, when building the same project under Xcode 16, the title bar is shown with the center contents of the navigation bar in the right pane being duplicated in the title bar (see screenshot at the end), which is undesirable. The screenshots for both builds were taken in macOS Sequoia Beta Seed 1. The Catalyst Interface setting is configured to "Optimize for Mac" in the project file. The scene's titlebar.titleVisibility property is set to .hidden, titlebar.toolbar is set to nil. UINavigationBar's appearance is configured with a preferredBehaviorStyle of .pad when running under Catalyst 16 or later. Is this a bug or am I missing a flag or something that was introduced to Catalyst/UIKit that I've overlooked? I've also filed a feedback for this issue: FB14000006. Thank you for your time.
0
0
66
4d
IOS 17.4 - 17.5 bug on copy html type of text
Hello we have created a function that is expanding copy module to support html format. Everything inside that function works fine but on 17.4+ IOS version copying the html element strike-through tag is not working (other HTML elements are working fine) . Looking the logs seems like are getting stripped. Here is the code: void copyToClipboard(NSString *htmlContent) { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; [pasteboard setValue:htmlContent forPasteboardType:@"public.html"]; } Does anyone know fix for this or when this will be fixed or will it be fixed in next update?
0
0
70
5d