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

UIKit Documentation

Posts under UIKit subtopic

Post

Replies

Boosts

Views

Activity

UITextView's pressesBegan isn't triggered by the software keyboard
I'm building a SwiftUI app with a UITextView subclass, and it seems that the software keyboard doesn't trigger the pressesBegan or pressesEnded functions of UITextView. With a hardware keyboard, pressesBegan works as expected, allowing us to intercept key presses in our subclass. I can't find any documentation about this, or any other forum posts (here or on Stack Overflow) that talk about a discrepancy between software and hardware keyboard behaviors, and I can't believe this is an intended behavior. Our app is a SwiftUI app, in case that's relevant. Does anyone have any guidance? Is this a bug or am I not understanding this API? Any information or work arounds would be greatly appreciated. I've made a sample project that demonstrates this issue, which you can grab from GitHub at https://github.com/nyousefi/KeyPressSample. To see this in action, run the sample project and start pressing keys. The hardware keyboard will print the key press at the top of the screen (above the text view), while the software keyboard won't.
3
0
644
May ’25
iOS UILabel textAlignment .justified results in wrong rect by layoutManager.boundingRect
I have a UILabel subclass showing NSAttributedString in which I need to draw a rounded rectangle background color around links: import UIKit class MyLabel: UILabel { private var linkRects = [[CGRect]]() private let layoutManager = NSLayoutManager() private let textContainer = NSTextContainer(size: .zero) private let textStorage = NSTextStorage() override func draw(_ rect: CGRect) { let path = UIBezierPath() linkRects.forEach { rects in rects.forEach { linkPieceRect in path.append(UIBezierPath(roundedRect: linkPieceRect, cornerRadius: 2)) } } UIColor.systemGreen.withAlphaComponent(0.4).setFill() path.fill() super.draw(rect) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { numberOfLines = 0 adjustsFontForContentSizeCategory = true isUserInteractionEnabled = true lineBreakMode = .byWordWrapping contentMode = .redraw clearsContextBeforeDrawing = true isMultipleTouchEnabled = false backgroundColor = .red.withAlphaComponent(0.1) textContainer.lineFragmentPadding = 0 textContainer.maximumNumberOfLines = numberOfLines textContainer.lineBreakMode = lineBreakMode textContainer.layoutManager = layoutManager layoutManager.textStorage = textStorage layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) } override func layoutSubviews() { super.layoutSubviews() calculateRects() } private func calculateRects(){ linkRects.removeAll() guard let attributedString = attributedText else { return } textStorage.setAttributedString(attributedString) let labelSize = frame.size textContainer.size = labelSize layoutManager.ensureLayout(for: textContainer) let textBoundingBox = layoutManager.usedRect(for: textContainer) print("labelSize: \(labelSize)") print("textBoundingBox: \(textBoundingBox)") var wholeLineRanges = [NSRange]() layoutManager.enumerateLineFragments(forGlyphRange: NSRange(0 ..< layoutManager.numberOfGlyphs)) { _, rect, _, range, _ in wholeLineRanges.append(range) print("Whole line: \(rect), \(range)") } attributedString.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedString.length)) { value, clickableRange, _ in if value != nil { var rectsForCurrentLink = [CGRect]() wholeLineRanges.forEach { wholeLineRange in if let linkPartIntersection = wholeLineRange.intersection(clickableRange) { var rectForLinkPart = layoutManager.boundingRect(forGlyphRange: linkPartIntersection, in: textContainer) rectForLinkPart.origin.y = rectForLinkPart.origin.y + (textContainer.size.height - textBoundingBox.height) / 2 // Adjust for vertical alignment rectsForCurrentLink.append(rectForLinkPart) print("Link rect: \(rectForLinkPart), \(linkPartIntersection)") } } if !rectsForCurrentLink.isEmpty { linkRects.append(rectsForCurrentLink) } } } print("linkRects: \(linkRects)") setNeedsDisplay() } } And I use this as such: let label = MyLabel() label.setContentHuggingPriority(.required, for: .vertical) label.setContentHuggingPriority(.required, for: .horizontal) view.addSubview(label) label.snp.makeConstraints { make in make.width.lessThanOrEqualTo(view.safeAreaLayoutGuide.snp.width).priority(.required) make.horizontalEdges.greaterThanOrEqualTo(view.safeAreaLayoutGuide).priority(.required) make.center.equalTo(view.safeAreaLayoutGuide).priority(.required) } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .justified let s = NSMutableAttributedString(string: "Lorem Ipsum: ", attributes: [.font: UIFont.systemFont(ofSize: 17, weight: .regular), .paragraphStyle: paragraphStyle]) s.append(NSAttributedString(string: "This property controls the maximum number of lines to use in order to fit the label's text into its bounding rectangle.", attributes: [.link: URL(string: "https://news.ycombinator.com/") as Any, .foregroundColor: UIColor.link, .font: UIFont.systemFont(ofSize: 14, weight: .regular), .paragraphStyle: paragraphStyle])) label.attributedText = s Notice the paragraphStyle.alignment = .justified This results in: As you can see, the green rect background is starting a bit further to the right and also ending much further to the right. If I set the alignment to be .left or .center, then it gives me the correct rects: Also note that if I keep .justified but change the font size for the "Lorem Ipsom:" part to be a bit different, lets say 16 instead of 17, then it gives me the correct rect too: Also note that if we remove some word from the string, then also it starts giving correct rect. It seems like if the first line is too squished, then it reports wrong rects. Why is .justified text alignment giving me wrong rects? How can I fix it?
Topic: UI Frameworks SubTopic: UIKit
0
0
41
May ’25
iOS app crash with UIKitcore - UIAlertController
I have recently submitted a new app version to the Appstore with Xcode 15.0. Unfortunately, I have started to see the below crash in the Xcode organiser &gt; Crashes section occurring for more number of times. UIKitCore: +[UIAlertController _alertControllerContainedInViewController:] + 160 The exception trace is not leading to main() function but not pointing to any of the code line. I had used UIAlertController in the past versions to show the alerts but there is no code written in the current version code related to UIAlertController. Only from the latest version, this kind of crash started to surface. In the latest release, We have added a third party SDK and while implementing the SDK, we had added the Location and Bluetooth Permissions in Info.plist file. But as we don't want to use/track the Location and Bluetooth details from the app, the SDK team has disabled the Location and Bluetooth settings to not reflect in the tracked data. Is this behaviour creating any conflict with the UIAlertController and logging the crash? Because by default the OS tries to show the alert when the permissions exist in the plist file, but the alert will not come as the service is disabled on the SDK server settings. Is this creating any conflict and logging the crash. Please extend your help.
3
0
802
May ’25
How to prevent iOS VoiceOver from speaking accessibility-labels and traits?
I have a button with the following properties: accessibilityLabel: "Action Button", traits: "Button", accessibilityHint: "Performs the main action". The voiceover reads the button as follows: Action Button, Button, Performs the main action. I want to understand how to configure it to only speak the accessibilityHint or only the accessibilityLabel and never speak the traits. In another example, a switch has the traits: Button, and Toggle. So these traits are a part of what the voiceover speaks. I want only the accessibilityLabel or accessibilityHint to be spoken in this case. Please let me know how. Thanks
1
0
50
May ’25
How to Use AccessorySetupKit to Automatically Trigger Hardware Pairing Screen in the Background?
Hello everyone, I’m currently developing an iOS app and would like to leverage the AccessorySetupKit framework introduced in iOS 18 to implement pairing functionality with our company's custom hardware product. The specific requirements are as follows: Our hardware supports both Bluetooth and Wi-Fi connections, and both are enabled. When the hardware device is in proximity to an iPhone, I want the device to be automatically recognized, and a pairing screen similar to the one in AccessorySetupKit should appear. Users should be able to perform the pairing process without needing to open our app, even if the app is not in the foreground. The system-level pairing screen should show the hardware information and allow the user to proceed with the pairing. My questions are: Does AccessorySetupKit allow the pairing screen to trigger when the app is running in the background, or must the app be in the foreground? How should I configure AccessorySetupKit to automatically recognize and display my company’s hardware device information? Are there any specific configurations or code implementations needed? Do I need to implement any specific Bluetooth/Wi-Fi advertising broadcasts to ensure the device is correctly detected by the iOS system when in proximity? Are there any additional permissions or configurations required, especially for handling background tasks? Thank you very much for your help, and I look forward to your advice and insights!
Topic: UI Frameworks SubTopic: UIKit
0
0
31
May ’25
Occasional Keyboard Cannot Hide in iOS16.5
Help,I have encountered a thorny problem! In systems with iOS 16.5 and above, there is a probability that the keyboard will not disappear after it appears. And once it appears, unless the app is restarted, all places where the keyboard is used cannot be closed. I have tried using the forced shutdown method [UIView endEditing:YES], but it didn't work. When this exception occurs, I notice that there will be two UITextEffectsWindow at the same time. Does anyone know how to solve it?
Topic: UI Frameworks SubTopic: UIKit Tags:
1
2
300
May ’25
UIViewRepresentable never dismantled on deletion (MEMORY LEAK)
I have find out that a UIViewRepresentable, even with a simples UIView, seems to never be dismantled when deleted from a ForEach and this can cause serious crashes. In the following example you can observe this behavior by deleting a row from the list. The dismantleUIView function of SomeUIViewRepresentable or the deinit of SomeUIView are never called. Has anyone faced this and found a solution for it? I have also filled a Feedback: FB11979117 class SomeUIView: UIView {     deinit {         print(#function)     } } struct SomeUIViewRepresentable: UIViewRepresentable {     func makeUIView(context: Context) -> SomeUIView {         let uiView = SomeUIView()         uiView.backgroundColor = .systemBlue         return uiView     }     func updateUIView(_ uiView: SomeUIView, context: Context) { }     static func dismantleUIView(_ uiView: SomeUIView, coordinator: Coordinator) {         print(#function)     } } struct Model: Identifiable {     let id = UUID() } struct ContentView: View {     @State var models = [Model(), Model(), Model(), Model(), Model()]     var body: some View {         List {             ForEach(models) { _ in                 SomeUIViewRepresentable()             }             .onDelete {                 models.remove(atOffsets: $0)             }         }     } }
1
2
1.4k
May ’25
Tab bar inline icon text .compact mode in size classes in iPad in iOS 18..4.1
I am trying to do inline to icon and text in tab bar but it is not allowing me to do it in compact, but it showing me in regular mode , but in regular mode tab bar going at top in portrait mode , But my requirement is tab bar required in bottom with icon and text in inline it showed by horizontally but it showing to me stacked vertically, will you guide me on this so that I can push the build to live users.
0
0
49
May ’25
iOS 18.4.1 Keyboard Extension Dark Mode Background Issue
Background Color Issue in Custom Keyboard Extension in Dark Mode for iOS 18.4.1 Issue Description I'm developing a custom keyboard extension for iOS 18.4.1 and experiencing an issue with background colors when using Dark Mode. After a user makes a selection from a menu in the keyboard, the background color of a view unexpectedly changes to white instead of maintaining the dark theme color. Steps to Reproduce Enable Dark Mode on the device Activate the custom keyboard in any text field Perform a specific interaction (selecting an item from a menu) After selection, the background of the view turns white instead of remaining dark Technical Details The issue appears to be related to UIScrollView's background color behavior The problem doesn't occur on initial display of the menu, only after user interaction I've attempted to set background colors explicitly on the view hierarchy, but the issue persists Environment iOS 18.4.1 Xcode 16.0 Custom keyboard extension Questions Has anyone encountered similar issues with view background colors changing after user interactions in keyboard extensions on iOS 18.4.1? Is there a recommended approach to maintain dark background colors in keyboard extensions after user selections? Could this be related to a change in how UIScrollView handles background colors in recent iOS versions? Thank you for any assistance or insights.
Topic: UI Frameworks SubTopic: UIKit
0
0
43
May ’25
UserDefaults.standard was cleared and app UUDI is also changed when I update new version from app store
Facing issue of NSUserDefaults data got cleared on update new version from app store. so all data of user got cleared and user have to login again. I was having app in store with version 1.1.3 and then we have uploaded new version to store with version 1.1.4 but when user download app from store their data was cleared from UserDefaults.so this is big issue in update. need to help. is that apple updated any process on update. Question How Apple change version build in device when we update app from app store. is it uninstall old build and install new build ? Or it is install new version on old version ? Should UserDefaults.standard will delete on update ? Updating Provisioning profile from manual to automatically cause issue on UserDefaults.standard Like UserDefaults got cleared and uuid will change ? Do we have anythings that we can identify specific user as uniq user ? What is better solution to store login data into SQLite store or in UserDefaults as model ? Will appreciate for your help. this is very big issue and login again on update will make app user more effect
4
1
3.8k
May ’25
How do I size a UITextView with scroll disabled?
tl;dr: UITextView does not auto layout when isScrollEnabled = false I have a screen with multiple UITextViews on it, contained within a ScrollView. For each textview, I calculate the height needed to display the entire content in SwiftUI and set it using the .frame(width:height:) modifier. The UITextView will respect the size passed in and layout within the container, but since UITextView is embedded within a UIScrollView, when a user attempts to scroll on the page, often they will scroll within a UITextView block rather than the page. They currently need to scroll along the margins outside of the textview to get the proper behavior. Since I am already calculating the height to display the text, I don't want the UITextView to scroll. However, when I set isScrollEnabled = false, the text view displays in a single long line that gets truncated. I have tried Setting various frame/size attributes but that seems to have zero affect on the layout. Embedding the textView within a UIView, and then sizing the container, but then the textView does not display at all. Setting a fixed size textContainer in the layoutManager but did not work. There's a lot of code so I can't copy/paste it all, but generally, it looks like struct SwiftUITextEditor: View { @State var text: AttributedString = "" var body: some View { ZStack { MyTextViewRepresentable(text: $text) } .dynamicallySized(from: $text) } } struct MyTextViewRepresentable: UIViewRepresentable { @Binding var text: AttributedString let textView = UITextView(usingTextLayoutManager: true) func makeUIView(context: Context) -> UITextView { textView.attributedText = text textView.isScrollEnabled = false } ... }
1
0
66
May ’25
New UIButton title left aligned
Hello There, I was trying to do a Button with title left aligned. With the old UIButton, I would have used the title-/contentEdgeInsets to achieve this, but with the new button these values are deprecated and do not work anymore. As far as I understood, with the new button only the spacing between the elements (sub-, title and image) is controllable. I also tried just setting the buttons width to the same width as the label, what would be possible in my case since it should be kind of a "hyperlink-button" which has no background or border. This works so far, but once the user interacts with the button, the title label gets multiline, which is on the one hand not wanted and on the other hand of course does not look left aligned anymore. (Besides the buttons height is fix in my case which leads to clipping of the title) So here again in short: Is there any way to make the title of the new UIButton left aligned inside of the button? Thank you very much in advance.
2
0
1.6k
May ’25
SIGTRAP crash in CoreGraphics font rendering pipeline (iOS 18.4)
We're observing new crashes specifically on iOS 18.4 devices with this pattern: Exception Type: SIGTRAP Exception Codes: fault addr: 0x000000019bc0f088 Crashed Thread: 0 Thread 0 0 libsystem_malloc.dylib _xzm_xzone_malloc_from_tiny_chunk.cold.1 + 36 1 libsystem_malloc.dylib __xzm_xzone_malloc_from_tiny_chunk + 612 2 libsystem_malloc.dylib __xzm_xzone_find_and_malloc_from_tiny_chunk + 112 3 libsystem_malloc.dylib __xzm_xzone_malloc_tiny_outlined + 312 4 CoreGraphics CG::Path::Path(CG::Path const&) + 132 5 CoreGraphics _CGPathCreateMutableCopyByTransformingPath + 112 6 CoreGraphics _CGFontCreateGlyphPath + 144 7 CoreGraphics _CGGlyphBuilderLockBitmaps + 1112 8 CoreGraphics _render_glyphs + 292 9 CoreGraphics _draw_glyph_bitmaps + 1116 10 CoreGraphics _ripc_DrawGlyphs + 1464 11 CoreGraphics CG::DisplayList::executeEntries(std::__1::__wrap_iter<std::__1::shared_ptr<CG::DisplayListEntry const>*>, std::__1::__wrap_iter<std::__1::shared_ptr<CG::DisplayListEntry const>*>, CGContextDelegate*, CGRenderingState*, CGGStack*, CGRect const*, __CFDictionary const*, bool) + 1328 12 CoreGraphics _CGDisplayListDrawInContextDelegate + 340 13 QuartzCore _CABackingStoreUpdate_ + 612 14 QuartzCore ____ZN2CA5Layer8display_Ev_block_invoke + 120 15 QuartzCore -[CALayer _display] + 1512 16 QuartzCore CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 420 17 QuartzCore CA::Context::commit_transaction(CA::Transaction*, double, double*) + 476 18 QuartzCore CA::Transaction::commit() + 644 19 UIKitCore ___34-[UIApplication _firstCommitBlock]_block_invoke_2 + 36 20 CoreFoundation ___CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 21 CoreFoundation ___CFRunLoopDoBlocks + 352 22 CoreFoundation ___CFRunLoopRun + 868 23 CoreFoundation _CFRunLoopRunSpecific + 572 24 GraphicsServices _GSEventRunModal + 168 25 UIKitCore -[UIApplication _run] + 816 26 UIKitCore _UIApplicationMain + 336 27 app _main + 132 28 dyld __dyld_process_info_create + 33284 Key Observations: Crash occurs during font glyph path creation (CGFontCreateGlyphPath) Involves memory allocation in malloc's xzone implementation 100% reproducible on iOS 18.4, not seen in prior OS versions Occurs during standard CALayer rendering operations Not tied to any specific font family or glyph content Questions for Apple: Is this crash signature recognized as a known issue in iOS 18.4's CoreGraphics? Could changes to xzone memory management in iOS 18.4 interact poorly with font rendering? Are there specific conditions that might trigger SIGTRAP in CGPathCreateMutableCopyByTransformingPath? Any recommended mitigations for text rendering while awaiting system updates?
2
3
430
May ’25
iOS 18.4 Beta: On iPhones which support Dynamic Island, the AppDelegate method applicationDidBecomeActive() takes longer to be called.
When testing with iOS 18.4 Beta on iPhones which support Dynamic Island, after doing a Face ID authentication, the amount of time it takes before the AppDelegate method applicationDidBecomeActive() is called takes longer than iPhones that do not support Dynamic Island. The time it takes is about double, 1.2 seconds vs 2.5 seconds on average. This does not occur with versions before 18.4 Beta. Anyone else seeing this?
Topic: UI Frameworks SubTopic: UIKit
2
3
318
May ’25
UITextView crash on iOS 18.4 beta
UITextView crash when setting attributed text that contains substring ffi and attributedText contains NSFontAttributeName, NSForegroundColorAttributeName Reproducible case: UITextView *textView = [[UITextView alloc] init]; textView.attributedText = [[NSAttributedString alloc] initWithString:@"ffi" attributes:@{ NSParagraphStyleAttributeName: [self createParagraphOfLineHeight:20], NSFontAttributeName: [UIFont systemFontOfSize:fontSize weight:UIFontWeightRegular], NSForegroundColorAttributeName: UIColor.black }];
Topic: UI Frameworks SubTopic: UIKit Tags:
9
2
1.9k
May ’25
When presenting CPNavigationAlert the navigation bar will appear
In my CarPlay app, I am hiding the navigation bar by using the following: self.mapTemplate?.automaticallyHidesNavigationBar = true self.mapTemplate?.hidesButtonsWithNavigationBar = false I don't want the navigation bar to show unless a user interacts with the map by tapping it. Strangely, when I present a CPNavigationAlert the navigation bar will often appear and then disappear after the alert is dismissed. Is there a setting or reason that the navigation bar would be appearing when presenting this alert? I would like to keep the nav bar hidden during this time.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
38
May ’25
cannot save event
iOS 18.4.1 When I change a Google type event to an iCloud type, a "Cannot Save Event" prompt box pops up. We have also received user feedback that recurring events also fail to save. After updating to iOS 18.4 when trying to save changes to an existing repeating event, the message "Cannot Save Event" will appear. EventKitUI
Topic: UI Frameworks SubTopic: UIKit
0
0
44
May ’25