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

UIKit Documentation

Post

Replies

Boosts

Views

Activity

Changing presentation style crashes app
Hello! I've been digging into this for a little bit now, and am hitting something of a wall. Our app is crashing occasionally, and googling the crash yields literally 0 results. Tl;dr: Something related to adaptivePresentationStyle(for:traitCollection:) is resulting in our app crashing. Context In our app, we have a custom UIPresentationController that we use to present a small sheet of content overlaying other app content - similar to a UISheetPresentationController with a medium-ish size. So we have a custom UIViewController to present, and it conforms to the UIAdaptivePresentationControllerDelegate protocol. We also have custom present and dismiss animators. The crash However, we seem to be running into a really odd crash. I've attached a crash report as well, but here's what one sees in xcode on reproducing the crash: The _computeToEndFrameForCurrentTransition block is nil inside the _transitionViewForCurrentTransition block, value of outerStrongSelf currently : <XxxYyyyyyZzz.PopupPresentationController: 0x12d017a40>. This most likely indicates that an adaptation is happening after a transtion cleared out _computeToEndFrameForCurrentTransition. Captured debug information outside block: presentationController : <XxxYyyyyyZzz.PopupPresentationController: 0x12d017a40> presentedViewController : <XxxYyyyyyZzz.SomeViewController: 0x12d03a690> presentingViewController : <UINavigationController: 0x12a817400> 2023-09-25_08-02-33.6523_-0500-7d355cd4a86427213389765ef070a777c4b4aaa3.crash Whenever we present one of these view controllers, things work just fine. When we try to present another one though, if someone is aggressively changing the phone orientation, the app crashes. This crash occurs somewhere in between dismissing the old VC and presenting the new one. It occurs before I ever hit any breakpoints in the "present" animator for the second view controller. I've narrowed things down a bit, and by commenting out our implementation of adaptivePresentationStyle(for:traitCollection:), the crash can't be reproduced anymore. The downside there being that the app no longer functions how we want it to. Our definition of that function (which causes crashes) looks like this: public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { guard forceUsingFullScreenIfCompact else { return .none } return traitCollection.verticalSizeClass == .compact ? .overFullScreen : .none } A bit more testing, and it seems like if that function returns the same thing consistently, nothing crashes. Are we not allowed to put conditional logic in this function? In the crash, we can see that it occurs due to a failing assertion internal to UIPresentationController: Last Exception Backtrace: 0 CoreFoundation 0x1afa28cb4 __exceptionPreprocess + 164 (NSException.m:202) 1 libobjc.A.dylib 0x1a8abc3d0 objc_exception_throw + 60 (objc-exception.mm:356) 2 Foundation 0x1aa1b2688 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 172 (NSException.m:251) 3 UIKitCore 0x1b1d05610 __80-[UIPresentationController _initViewHierarchyForPresentationSuperview:inWindow:]_block_invoke + 2588 (UIPresentationController.m:1594) 4 UIKitCore 0x1b21f1ff4 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke_3 + 300 (UIPresentationController.m:1228) The question This all leads us to wonder if we're doing something wrong, or if there could be a bug in one of the iOS APIs that we're consuming. Thus, posting here. Does anyone have any insight into how this could be occurring, or has seen this before and has ideas? Thanks! Miscellaneous info We target iOS 14+ We've seen this issue in debug and release builds from Xcode 14 and 15 We see the issue on users with iOS 15+, though it could be occurring on 14 in just incredibly low numbers This is a re-post of https://developer.apple.com/forums/thread/738257, because I accidentally closed that out as resolved
3
2
793
Dec ’23
Help with crash in objc_msgSend (no app code in stack trace)
Hello, I am attempting to track down a crash that isn't giving me a lot of information (crash log included below). Here is what I know so far: According to Apple documentation, a crash in objc_msgSend is due to a zombie object. So I have been trying to recreate the crash with zombies enabled, without success. The address of the object being messaged is 0x0000000000000010, a suspect value. It's always 0x10, across thousands of crash reports with slightly differing stack traces and circumstances. That makes me wonder if the runtime is trying to tell me something with that address, but I have been unable to find any documentation to that effect. We have internal analytics that suggest that the crash always happens after the user activates the system PIP video player, and usually also after backgrounding the app. It is also common (though not universal) that the crash occurs after the user has paused the video (and sometimes resumed it). This post is a bit of a Hail Mary; I'm hoping that maybe someone on here will see something I missed, because I have exhausted most of my own avenues of investigation. Many thanks for any help you can provide. 2023-11-30_07-16-00.4347_-0800-ffd5dc1a3d2ca628e1761ccfec5fe79f223d099e.crash
3
0
1.8k
Dec ’23
MFMessageComposeViewController cannot send special characters via iOS 17
I have a text in the application that comes with special characters (the text is written in French) that I want to send using MFMessageComposeViewController. I define the text in the body field: messageComposeVC.body = body and call to present the message compose like that : UIApplication.topViewController()?.present(messageComposeVC, animated: true, completion: nil) The message/imessage open and display the preview with the text i defined. But, since the upgrade of the iPhone to ios 17 it stopped working, when i send the message the message was not send and I received a message that the message failed. I also tested on ios 16 - it works great. Any idea how i can fix it?
0
0
849
Dec ’23
How to disable scroll animation for UITextField?
Yes, I mean UITextField. Howdy, Is there a way to disable the animation that occurs to a UITextField with long content after it becomes first responder? Specifically the one that sort of slow scrolls to the end of the content. Here's a video of the animation I am trying to describe https://www.youtube.com/watch?v=9l2tUrxW_qY . Notice how the textfield transitions from "a" to "." as it moves to the end of the content? Ideally, I would like the UITextField to simply appear on the screen like it does in the final frame of the animation, showing the final part of the content. Thanks, smkuehnhold
0
0
401
Dec ’23
How to handle UIPhysicalKeyboardEvent?
I'm trying to improve our application to receive and handle events from a bluetooth keyboard. To intercept incoming events I use sendEvent: method. But I get a different event type for a different key. For example when I press 'Esc' key I get an event type is UIEventTypePresses (and event is a instance of UIPressesEvent class) but when I press 'ArrowUp' key I get an event type is 4 (there is no enum value for that number) and event is a instance of UIPhysicalKeyboardEvent class. In the first case I found a documentation of UIPressesEvent and I can implement handler for it. But for the second case I didn't find any documentations of UIPhysicalKeyboardEvent nether in the online documentation nor in the Xcode help. How can UIPhysicalKeyboardEvent events be handled? Is the any documentation for that? My target OS is tvOS 17.1
1
0
579
Dec ’23
UIKit Document App -- adding a toolbar
I've had to ditch the SwiftUI app lifecycle due to this issue: https://developer.apple.com/forums/thread/742580 After creating a new UIKit document app as a test, it doesn't have a toolbar when opening the document. How can I add one along the lines of https://developer.apple.com/wwdc22/10069 ? The UIDocumentViewController isn't already embedded in a UINavigationController it seems. To reproduce: New Project -> iOS -> Document App. Select Interface: Storyboard. Add an empty "untitled.txt" resource to the project. Change the first line in documentBrowser(_:,didRequestDocumentCreationWithHandler:) to let newDocumentURL: URL? = Bundle.main.url(forResource: "untitled", withExtension: "txt")
2
0
503
Dec ’23
Why UIActivityViewController navigationBar backgroundColor is clear?
Under iOS 17, I need to set view.backgroundColor when using UIActivityViewController, otherwise the navigationBar will be transparent. (iOS 17 does not have this problem) I have checked many tutorial examples but this situation is not mentioned. Is there any implementation missing from my code? Sample Code: let sharedURL = URL(string: "...")! let activityVC = UIActivityViewController(activityItems: [sharedURL], applicationActivities: nil) present(activityVC, animated: true) Sample Image:
1
0
302
Dec ’23
Changing font in CollectionView UIIndexBarAccessoryView
I have a 600 item Collection view for which I implemented a quick access section Index. The implementation uses the usual: indexTitles(for collectionView) and CollectionView(indexPathForIndexTitle: title: at:) All is well, except that the collection titles are in a foreign language (latinized Coptic) and 3 of the 25 title glyphs are not in the SystemFont, so the index is drawn with these titles as question marks in boxes. The problem glyphs are "Ꜣ"(unicode A722), "꟣"(A7E3), and "Ꜥ"(A725) I drilled down on the subviews of the CollectionView and found I could access the index using: let subviews = myCollectionView.subviews if let indexView = subviews.first(where: {String(describing: type(of: $0))=="UIIndexBarAccessoryView"}) { print(indexView) } Examining the contents of this UIIndexBarAccessoryView (which seems to be Private), it contains a _visualStyle property object which holds a _font. How can I "legally" change the font for the indexBarAccessory to one that has the required glyphs? The rest of the App requires the local language to be English(US)
0
0
324
Dec ’23
black screen after switching to UIKit app lifecycle
I had to switch from the SwiftUI app lifecycle to the UIKit lifecycle due to this issue: https://developer.apple.com/forums/thread/742580 When I switch to UIKit I get a black screen on startup. It's the inverse of this issue: https://openradar.appspot.com/FB9692750 For development, I can work around this by deleting and reinstalling the app, but I can't ship an app that results in a black screen for users when they update. Anyone know of a work-around? I've filed FB13462315
3
1
925
Dec ’23
SwiftUI TabBar Icons Disappearing
I have a UIKit tabbar view that contains three views, one of which is a UIViewControllerRepresentable wrapper around a UIKit view controller. Everything works fine except when that wrapped view is visible, the tab bar icons for the other two views disappear. Tapping within their bounds still works to select those views as expected, and they’re even visible in screenshots and in the debug view of the view hierarchy (they also display normally when running the iPad version of the app on Mac), so I’m not sure where to turn except perhaps a bug report. Is this a known issue when running UIKit views within a SwiftUI TabBar or where should I look next?
2
0
726
Dec ’23
Custom keyboard randomly crash with NSExtension Error
I'm currently developing a custom keyboard which bundled with main app. The keyboard would randomly crash when switch between apps with opened custom keyboard on physical device. I've read posts around but seems not what I've encountered. Bundle ID of main app: com.company.appName Bundle ID of keyboard extension: com.company.appName.Keyboard When custom keyboard is opened second time on other app, a sole personality warning would show up, but this won't lead to crash. WARNING! Sole personality is ambiguous; this may lead to erratic behavior [lifecycle] [u 9A2D7B1D-20AF-4E2A-A72F-C37C8D4FDEEA] [com.company.appName.Keyboard(1.0.0)] WARNING! Sole personality is ambiguous; this may lead to erratic behavior; personalities: { "com.companyName.appName.keyboard" = { 19209 = "&lt;PKServicePersonality: 0x28299da00; core = &lt;[u 9A2D7B1D-20AF-4E2A-A72F-C37C8D4FDEEA] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]&gt;, host pid = 19209&gt;"; 19293 = "&lt;PKServicePersonality: 0x28298fb00; core = &lt;[u DA59190E-D8A2-4109-8D7B-1702E03AB0BD] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]&gt;, host pid = 19293&gt;"; 299 = "&lt;PKServicePersonality: 0x282981700; core = &lt;[u 61DC0533-3D02-4CE7-83C2-D698537BC6ED] [com.company.appName.Keyboard(1.0.0)],[d (null)] [/private/var/containers/Bundle/Application/67892ACC-5BDA-4205-828D-4D94D6E87ABD/AppName.app/PlugIns/Keyboard.appex]&gt;, host pid = 299&gt;"; }; } After switching between apps for few times, the custom keyboard would crash, common crash log is : Connection to plugin invalidated while in use. 2023-12-13 10:19:44.220973+0800 MobileNotes[36435:1892265] [lifecycle] [u 9A37D3B6-CAE5-4E5C-95FF-DA653DC080E5:m (null)] [com.companyName.appName.Keyboard(1.0.0)] Connection to plugin interrupted while in use. 2023-12-13 10:19:44.221229+0800 MobileNotes[36435:1892265] [lifecycle] [u 9A37D3B6-CAE5-4E5C-95FF-DA653DC080E5:m (null)] [com.companyName.appName.Keyboard(1.0.0)] Connection to plugin invalidated while in use. Another crash log is bit more detailed, but still not sure what it may refers to. ` 2023-12-13 10:19:44.222563+0800 MobileNotes[36435:1892256] [NSExtension] Unable to setup extension context - error: Couldn’t communicate with a helper application. 2023-12-13 10:19:44.222646+0800 MobileNotes[36435:1892256] [NSExtension] Async Begin using internal completion handler called multiple times. Due to error after initial completion: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.company.appName.Keyboard.apple-extension-service" UserInfo={NSDebugDescription=connection to service named com.company.appName.Keyboard-extension-service} Program ended with exit code: 9`
1
0
651
Dec ’23
The format of UITextField is changed after clearing the text and inputting new text.
I have a UITextField and set its text format(font/color/underline) by UITextField.attributedText. However, when I clear the text than input text again, the format is changed. It seems the behavior of attributedText is reset by system after clearing the text. Is this a bug or can we have some workaround to keep the consistent format after clearing the text? The code snippet is like below: let textField = UITextField(frame: CGRectMake(0, 0, 200, 60)) let fontColor = .red let attrText = NSMutableAttributedString(string: "normal text") let range = NSRange(location: 0, length: attrText.length) attrText.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: range) attrText.addAttribute(.foregroundColor, value: fontColor, range: range) attrText.addAttribute(.underlineColor, value: fontColor, range: range) attrText.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range) textField.attributedText = attrText
1
0
312
Dec ’23
@available annotation forgotten in showsExpansionTextWhenTruncated
Our app has iOS deployment target as 13. We have used showsExpansionTextWhenTruncated property and is available to iOS 15+. Unfortunately we have used showsExpansionTextWhenTruncated property without if #available(iOS 15, *) and never was failed the build. However, there were many crashes because of that. Should UIKit implement @avaiable in showsExpansionTextWhenTruncated property?
1
0
275
Dec ’23
Are storyboard and UIKit due to disappear ?
I read in Xcode 15.2 release notes that @IBDesignable and @Inspectable are deprecated and will disappear in a future release. After the abandon of WatchKit and its storyboard, replaced by SwiftUI, does it mean storyboards (and consequently UIKit) will progressively disappear, leaving developers alone with SwiftUI to design apps (IMHO, inadequate to design complex UI: for instance, I always struggle to position precisely objects for all devices sizes as we miss constraints manager in SwiftUI) ? For sure, IBDesignable is (was) whimsical, but a very useful tool to design sophisticated UI. Replacing by #Preview does not make it. I also understand that Xcode is a very complex piece of code and that maintaining and evolving some tools (as IBDesignable) requires effort. But isn't it what we expect from Apple ? To provide us with the best tools and keep on the promise of WYSIWYG environments, all along ? Is it only me or do others share this view ?
2
0
1.8k
Dec ’23
UICollectionview Cell textview bounces up - when Keyboard is up and language is selected other than English.
Environment: iOS 15.7.5 Device: iPhone 7 Problem: When collectionview cell textview is in edit mode and keyboard is shown - it bounces up the textview position causing overlaps. Video attached. The issue only occurs on iOS 15 version. It works well in iOS 16, 17 version. The issue occurs when Selected keyboard language is other than English. In ViewController i am updating collectionViewBottomConstraint when keyboard is up or down to enable scroll to the end of collectionview when keyboard is shown. disposable += NotificationCenter.default.reactive .notifications(forName: UIResponder.keyboardWillShowNotification) .take(duringLifetimeOf: self) .observeValues { [weak self] notification in guard let self else { return } let keyboardInfo = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] guard var height = (keyboardInfo as? NSValue)?.cgRectValue.height else { OALogInfo("[SetLocationInfo][VC] height is nil") return } height -= self.view.safeAreaInsets.bottom self.collectionViewBottomConstraint.constant = -height self.collectionViewBottomConstraint.isActive = true } disposable += NotificationCenter.default.reactive .notifications(forName: UIResponder.keyboardWillHideNotification) .take(duringLifetimeOf: self) .observeValues { [weak self] notification in guard let self else { return } self.collectionViewBottomConstraint.constant = 0 self.collectionViewBottomConstraint.isActive = true }
0
0
334
Dec ’23
PKCanvasView: zoom+rotate gesture=ded performance
I'm trying to add rotation functionality to the PKCanvasView, so that rotation gesture rotates the drawing, I want it to be working together with zoom gesture too, which is already implemented in the PKCanvasView. Rotation works reasonably fine when rotation and zoom can't be performed simultaneously. The moment I enable simultaneous zoom+rotation performance of rotation gets noticably bad. Visually it looks like rotation only happens on noticable angles like 10,20,30.. degrees which looks choppy. Zoom at the same time looks smooth as before. I'm trying to understand why and how to fix this. The rotation gesture handler is here: @objc func handleRotation(_ gesture: UIRotationGestureRecognizer) { guard let curView = gesture.view as? PKCanvasView else {return} if gesture.state == .began || gesture.state == .changed { let rotation = gesture.rotation let gestureCenter = gesture.location(in: curView) let center = CGPoint(x: gestureCenter.x / curView.zoomScale, y: gestureCenter.y / curView.zoomScale) let finalTransform = CGAffineTransform(translationX: -center.x, y: -center.y) .concatenating(CGAffineTransform(rotationAngle: rotation)) .concatenating(CGAffineTransform(translationX: center.x, y: center.y)) curView.drawing.transform(using: finalTransform) gesture.rotation = 0 } } which just constructs rotation matrix around rotation gesture center and calls curView.drawing.transform(using: finalTransform). Rotation matrix is correct I think because without simultaneous zoom+rotation it rotates everything as intended and smoothly under any zoom. (Just for clarity: in the rotation handler the matrix does only the rotation, zoom is done in pinch gesture handler implemented by the PKCanvasView. The zoomScale is used in estimations only to figure out the content coodrinate). The handleRotation method is set as let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(handleRotation)) rotationGestureRecognizer.delegate = self canvasView.addGestureRecognizer(rotationGestureRecognizer) The simultaneous handling of zoom+rotation I enable with this code: func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } What I've tried: Tried to nable simultaneous recognition only for zoom+rotation (without the pan gesture and possible others), the effect is the same. For example rotation+pan work smoothly together. I've verified that the gesture handler is called very often, every 8-16 milliseconds (rotation matrix creation and curView.drawing.transform(using: finalTransform) is included in this time period) which should be enough for visually smooth rotation. Other observations: When zoom and rotation both are enabled the rotation sometimes gets completely stuck, zoom and pinch is responsive but rotation is not happening visually. Only when I release fingers from the screen the rotation unstucks and content is rotated as if it didn't stuck at all. During the "stuck" period the rotation handler is called with the same frequency it's just not being visually reflected. Other thoughts: It kind of looks like the tranformation I set in the rotation handler gets overwritten by transformation from the zoom handler. But pan+rotation works fine together which confuses this theory.
1
0
669
Dec ’23
How to update UIConfigurationState from CollectionView using UIConfigurationStateCustomKey
is there anybody using UIConfigurationStateCustomKey to manage custom state for cells? I want to know if that would be possible to update from the collection view, it’s like UICollectionView.select(indexPath) seems like there is no way for this though. currently UICollectionView (UITableView) can manage is-selected for cells. but provided official property are only available. if we need something another custom properties that describes the cell’s state, we might need make state manager for cells. I was wondering how UIConfigurationStateCustomKey works for us for such case. According to the documentation, we can update the custom state from only visible cell. so we can not update currently hidden cell’s state. https://developer.apple.com/documentation/uikit/uiconfigurationstatecustomkey
0
0
322
Dec ’23
UIHostingController wrong height animation
In iOS 17, whenever I change the height of a UIHostingController in a animation block, the root SwiftUI.View ignores it: class TestAnimationController: UIViewController { var heightConstraint: NSLayoutConstraint! // a basic trigger override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) heightConstraint.constant = heightConstraint.constant == 300 ? 100 : 300 UIView.animate(withDuration: 1.0) { self.view.layoutIfNeeded() } } override func viewDidLoad() { super.viewDidLoad() let content = UIHostingController(rootView: Color.red) addChild(content) view.addSubview(content.view) content.view.translatesAutoresizingMaskIntoConstraints = false heightConstraint = contentView.heightAnchor.constraint(equalToConstant: 100) heightConstraint.isActive = true contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true content.didMove(toParent: self) } } The result is terrible: It was not the case in iOS 14.5: Does someone have a workaround?
2
0
637
Dec ’23
UIAlertAction has a poor color contrast ratio in destructive style
Hi Folks, I am reaching out for an iOS A11y color contrast issue, which I have also fired a bug report 12525894 but does not get any reply. The UIAlertAction in destructive style has a poor color contrast ratio of less than 4.5: 1 between text color and background color. This applies to any system/third party app which uses UIAlertViewController from UIKit and Alert from SwiftUI (Take the system Photos app as an example). Given that the "titleTextColor" property from UIAlertAction class is private, developers have no ways to modify the alert action to make it WCAG compatible. Here is an example of the Photo app alert. The text "Delete Photo" (#EB4E3D) should have a contrast ratio of at least 4.5 to 1 against its background(#EAEBE7) to comply to the Web Content Accessibility Guidelines (WCAG). Actual result: The text "Delete Photo" (#EB4E3D) has a contrast ratio of 3.08 to 1 against its background(#EAEBE7), which does not match 4.5:1 Web Content Accessibility Guidelines (WCAG).
0
0
553
Dec ’23