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

UIKit Documentation

Posts under UIKit tag

968 Posts
Sort by:
Post not yet marked as solved
7 Replies
2.7k Views
Is it possible to present UIMenu programmatically in UIButton or UIBarButton? I have custom logic where I'd like to show that menu. I couldn't find any solution.
Posted
by VabererP.
Last updated
.
Post marked as solved
1 Replies
34 Views
I'm building a custom UIAccessibilityElement for a complex control, and would like to expose both the .adjustable UIAccessibilityTrait (to move between discrete members listed in the control) and accessibilityCustomActions (to enable multiple possible interactions). My (limited) experience is that both adjustment and custom action selection employ vertical swipes, so they collide if an element exposes both: vertical swipes call accessibilityIncrement and accessibilityDecrement, which I'm using to move between the members, and the accessibility element is described as having "Actions available" but there seems to be no way to access them. Is there a way, beyond reimplementing my increment and decrement methods to append the custom actions to the discrete element list somehow, to enable a user to interrogate both these extra dimensions on a single accessibility element?
Posted
by ibsh.
Last updated
.
Post not yet marked as solved
7 Replies
981 Views
Hi, I've recently experienced a weird crash that only happening on iOS 16 device (iOS 16.xx - 16.3). Here is the stack trace 0 libobjc.A.dylib 0x00000001bc11ae5c _objc_retain_x0 (in libobjc.A.dylib) + 16 1 UIKitCore 0x00000001c5c06a5c -[UIKeyboardTaskQueue promoteDeferredTaskIfIdle] (in UIKitCore) + 72 2 UIKitCore 0x00000001c5c069e8 -[UIKeyboardTaskQueue performDeferredTaskIfIdle] (in UIKitCore) + 28 3 UIKitCore 0x00000001c54039c8 -[UIKeyboardTaskQueue continueExecutionOnMainThread] (in UIKitCore) + 372 4 Foundation 0x00000001bd21484c ___NSThreadPerformPerform (in Foundation) + 260 5 CoreFoundation 0x00000001c2f31f30 ___CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ (in CoreFoundation) + 24 6 CoreFoundation 0x00000001c2f3e308 ___CFRunLoopDoSource0 (in CoreFoundation) + 172 7 CoreFoundation 0x00000001c2ec222c ___CFRunLoopDoSources0 (in CoreFoundation) + 336 8 CoreFoundation 0x00000001c2ed7b88 ___CFRunLoopRun (in CoreFoundation) + 832 9 CoreFoundation 0x00000001c2edcebc _CFRunLoopRunSpecific (in CoreFoundation) + 608 10 GraphicsServices 0x00000001fcf33364 _GSEventRunModal (in GraphicsServices) + 160 11 UIKitCore 0x00000001c53d2868 -[UIApplication _run] (in UIKitCore) + 884 12 UIKitCore 0x00000001c53d24cc _UIApplicationMain (in UIKitCore) + 336 13 News 0x00000001106d5d1c main (in News) (main.m:23) 14 dyld 0x00000001e16fe95c start (in dyld) + 2524
Posted
by Lyokooo.
Last updated
.
Post not yet marked as solved
1 Replies
73 Views
The feature is to upload photos via AWS and the keys are obtained from our respective servers to upload a photo in case the keys are expired. As per logs the app crashes in newProcessS3Upload line in the below func. Please find the complete stack trace in the attachment. crash_log.txt func newRetrieveS3Credentials(uploadObject:NSDictionary) { let type = uploadObject.object(forKey: "type") as? NSNumber ?? 0 guard let signatureUploadRequest:URLRequest = self.retrieveSignatureUploadURLRequest() else{ return } let defaultSession:URLSession = URLSession.shared let dataTask = defaultSession.dataTask(with: signatureUploadRequest, completionHandler: { data, response, error in if let httpResponse = response as? HTTPURLResponse, let data = data { if httpResponse.statusCode == 200 { do { let responseDictionary = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any] self.newCredentialsRetrieved(credentialsDict: responseDictionary ?? [:]) DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) { self.newProcessS3Upload(uploadObject: uploadObject) } } catch let jsonError{ self.log.i("S3Manager: Json serialzation error: \(String(describing: jsonError))") } } else { self.log.i("S3Manager: Error with S3 JSON request: \(error.debugDescription)") let delegate = uploadObject.object(forKey: "delegate") if let delegate = delegate as? S3Observer{ self.delegate = delegate } if type.intValue == UploadType.SIGNATURE_TYPE.rawValue { DispatchQueue.global(qos: .userInitiated).async { DispatchQueue.main.async { self.delegate?.signatureFailedToUpload?(forStop: self.uploadSignature?.stopId, withError: error.debugDescription) } } }else if type.intValue == UploadType.ITEM_PHOTO_TYPE.rawValue && ((self.delegate?.responds(to: #selector(S3Observer.errorOccured(_:)))) != nil) { self.delegate?.errorOccured?(error) } self.log.i("S3Manager: Unknown S3 upload Error: \(error.debugDescription)") } } }) dataTask.resume() } The crash log is as follows: Crashed: com.apple.root.default-qos 0 WISE Driver 0x14e4a4 S3Manager.newProcessS3Upload(uploadObject:) + 4331070628 (S3Manager.swift:4331070628) 1 WISE Driver 0x1520c4 partial apply for closure #1 in closure #1 in S3Manager.newRetrieveS3Credentials(uploadObject:) + 4331086020 (<compiler-generated>:4331086020) 2 WISE Driver 0x1409a8 thunk for @escaping @callee_guaranteed () -> () + 4331014568 (<compiler-generated>:4331014568) 3 libdispatch.dylib 0x3f88 _dispatch_client_callout + 20 4 libdispatch.dylib 0x7418 _dispatch_continuation_pop + 504 5 libdispatch.dylib 0x1aa58 _dispatch_source_invoke + 1588 6 libdispatch.dylib 0x6f54 _dispatch_queue_override_invoke + 500 7 libdispatch.dylib 0x15a6c _dispatch_root_queue_drain + 396 8 libdispatch.dylib 0x16284 _dispatch_worker_thread2 + 164 9 libsystem_pthread.dylib 0xdbc _pthread_wqthread + 228 10 libsystem_pthread.dylib 0xb98 start_wqthread + 8 com.apple.main-thread 0 libsystem_kernel.dylib 0xda8 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x13a1c mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x13c5c mach_msg_overwrite + 388 3 libsystem_kernel.dylib 0x12ec mach_msg + 24 4 CoreFoundation 0x7aac4 __CFRunLoopServiceMachPort + 160 5 CoreFoundation 0x7bd08 __CFRunLoopRun + 1232 6 CoreFoundation 0x80eb0 CFRunLoopRunSpecific + 612 7 GraphicsServices 0x1368 GSEventRunModal + 164 8 UIKitCore 0x3a1668 -[UIApplication _run] + 888 9 UIKitCore 0x3a12cc UIApplicationMain + 340 10 WISE Driver 0x46ac main + 14 (main.m:14) 11 ??? 0x1f5294960 (Missing) Your help is greatly appreciated. Thanks, DebWisesystems
Posted Last updated
.
Post not yet marked as solved
0 Replies
45 Views
Hi there, the documentation explicitly says this is what's contentView for. I've just tried and found big problems not adding — works like a charm — but positioning my view so that it does not clash with the standard ones. I've added a small badge at the rightmost edge of contentView. Having added the subview into contentView (in tableView:cellForRowAtIndexPath:, after checking that it does not exist yet in a reused cell view), I set up constraints so that it is Y-centered and sticks to the right edge of the contentView, that was very easy and worked nicely at the first try: UILayoutGuide *lg=cell.contentView.layoutMarginsGuide; [badge.trailingAnchor constraintEqualToAnchor:lg.trailingAnchor].active=YES; [badge.centerYAnchor constraintEqualToAnchor:lg.centerYAnchor].active=YES; I've found though if the text in textLabel (I have to address iOS12+, thus I can't use content configurations) is long enough, it clashes with the badge instead of clipping/wrapping/whatever it is set to (wrapping in my case). Thus I've added another constraint which makes sure the trailing edge of textLabel does not exceed the leading edge of my badge: UILayoutGuide *blg=badge.layoutMarginsGuide; [cell.textLabel.trailingAnchor constraintLessThanOrEqualToAnchor:blg.leadingAnchor constant:-6].active=YES; Oops: that pushed the badge right, so that it overlaps the accessory area. By my further testing, seems the culprit is another constraint (probably created dynamically later from the autoresizing mask) which bounds the right edge of textLabel to the right edge of contentView. I've tried to find and remove (deactivate) it in tableView:cellForRowAtIndexPath:, in vain, well, makes some sense perhaps, too soon. I've tried to find and remove it in tableView:willDisplayCell:forRowAtIndexPath:; no luck either. To me, this does not make sense at all. (It sort of looks like the documentation claim “After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out” is highly overstated. Self-evidently, non-trivial layout stuff happens after the delegate returns, but before the cell is drawn.) Eventually, having used updateConstraints explicitly (which does not feel right), I succeeded to find the darn thing, a fixed width constraint for textLabel. Tried to deactivate it: does not work, setting its active property to NO does nothing, no warning, no error, no exception, thing just stays at YES. I've tried to decrease its priority, that's even more funny: it goes down, when checked, it is down, but 1000 is somehow re-surrected after tableView:willDisplayCell:forRowAtIndexPath: returns, but before the cell is finally laid out and drawn. Ick. What's the proper solution of this? I suppose it should be pretty easy, but it is not, or I must be overlooking something pretty obvious. Thanks!
Posted
by OC_s.
Last updated
.
Post not yet marked as solved
1 Replies
86 Views
2023-03-15 16:49:27.504266-0400 Flip[32191:1879406] [WindowServer] Failed to register for CADisplay change notifications: 0x9 2023-03-15 16:49:27.505090-0400 Flip[32191:1879406] [WindowServer] Failed to register for CADisplay power notifications: 0x9 2023-03-15 16:49:27.549439-0400 Flip[32191:1879406] [Common] BKSAccelerometer unable to create notifyd token for device orientation 2023-03-15 16:49:27.549252-0400 Flip[32191:1879672] [default] Failed to register for server availability: 9 2023-03-15 16:49:27.736276-0400 Flip[32191:1879406] [Default] Unable to register for test daemon availability notification. 2023-03-15 16:49:27.737912-0400 Flip[32191:1879406] [Default] Unable to register token for checking test daemon availability. 2023-03-15 16:49:27.739657-0400 Flip[32191:1879406] [Default] Unable to register for test daemon availability notification. 2023-03-15 16:49:27.741339-0400 Flip[32191:1879406] [Default] Unable to register token for checking test daemon availability. 2023-03-15 16:49:27.743108-0400 Flip[32191:1879406] [Default] Unable to register for test daemon availability notification. 2023-03-15 16:49:27.745075-0400 Flip[32191:1879406] [Default] Unable to register token for checking test daemon availability. 2023-03-15 16:49:27.846015-0400 Flip[32191:1879666] [ServicesDaemonManager] invalidationHandler is called. -[FontServicesDaemonManager connection]_block_invoke_2 2023-03-15 16:49:27.846806-0400 Flip[32191:1879666] [ServicesDaemonManager] xpc error: -[FontServicesDaemonManager checkin:]_block_invoke - Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.fontservicesd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.fontservicesd was invalidated: failed at lookup with error 159 - Sandbox restriction.}
Posted
by SeleneMKS.
Last updated
.
Post not yet marked as solved
7 Replies
719 Views
We noticed that with Xcode 14 and iOS16+, when the app navigates to a view controller that has a UITextField getting focus in viewWillAppear() via calling becomeFirstResponder(), the transition starts on the right, then returns a bit back, then resumes, and the keyboard is moving at the same time, resulting in a noticeable visually jerking animation. This does not happen with Xcode 13, or with Xcode 14 when running under iOS15. Is this a known bug? Has someone else seen this behavior? Any ideas for a workaround? We tried disabling animations, but this does not work well. We can use viewDidAppear to display the keyboard after push animation is completed, but it takes a bit more time and not so nice as pushing the next view controller with already displayed keyboard.
Posted
by serge_o.
Last updated
.
Post not yet marked as solved
0 Replies
40 Views
I noticed that UITextViews get stuck in memory after a preview has been shown. I mean the preview you get when you long press a url. For this to work editable should be false and dataDetectorTypes should include .link. Include a url to the text and long press it. A preview should show. When you quit the preview and you remove the text view with removeFromSuperView() (or just close the ViewController containing the text view), it won't deinit anymore. You can check by overriding deinit or by checking if a weak reference (like IBOutlet) has become nil. I also noticed that two system ViewControllers stay in memory too, namely SFSafariViewController and SFBrowserRemoteViewController. I don't know if this is by design. Tried on iOS 16.2 and 16.3.1.
Posted Last updated
.
Post not yet marked as solved
1 Replies
172 Views
I am seeing call stacks originating from UIKit code crashing in _UIGetCurrentFallbackTraitCollection with a memory issue. Crash logs are attached. What could this be? My app uses UIAppearance, I suspect this to be related, but I cannot trace the crash logs back to app-specific code. report-2517277966970009999-a5c0cdc9-6616-4f57-87ba-3abe0a16d1dc (1).txt report-2517282597380009999-69132756-a7c8-4b56-9d4c-66742a73e294.txt report-2517281480860009999-0e385e9c-5f69-4ee2-af18-47f180fa814d.txt
Posted
by datwelk.
Last updated
.
Post marked as solved
2 Replies
656 Views
Hello! Thanks for taking your time to help others. Problem description: Our SwiftUI app min deployment is iOS 14. We've been struggling with status bar* color just in iOS 16. We can't change its color/appearance from light to dark. (*) For instance, this picture refers to what I think is status bar (may be obvious, yes). Previous valid solution (iOS 13 to iOS 15) Since now we used to manage the appearance with ... Call in specific view, when a condition is given, like no dark mode supported, or side menu have been open UIApplication.setStatusBarStyle(.darkContent) The extension to support this on any SwiftUI View import UIKit extension UIApplication { class func setStatusBarStyle(_ style: UIStatusBarStyle) { if let controller = UIApplication.getKeyWindow()?.rootViewController as? ContentHostingController { controller.changeStatusBarStyle(style) } } } Actually, the controller class import SwiftUI import UIKit class ContentHostingController: UIHostingController<AnyView> { private var currentStatusBarStyle: UIStatusBarStyle = .default override var preferredStatusBarStyle: UIStatusBarStyle { currentStatusBarStyle } func changeStatusBarStyle(_ style: UIStatusBarStyle) { self.currentStatusBarStyle = style self.setNeedsStatusBarAppearanceUpdate() } } But, as I said, this stopped working with iOS 16. What we have checked? As we googled it... Using .preferredColorScheme modifier, changes the app appearance, and we want to keep, for example, the dark theme along light status bar. So it's not an option. Applying .toolbarColorScheme (iOS 16), does nothing. Manage Info.plist without success. Light content by default, could be changed (with the method described above) Questions Why is this not working in iOS 16? Are we doing something wrong? (worked like a charm for 13 to 15). Is there any generic (iOS 13 to 16) way that you actually use and work? (If not) Do you know any workaround to apply on 16 only?
Posted Last updated
.
Post not yet marked as solved
1 Replies
65 Views
GOAL: I want to UI test my SegmentedControl - check that each segment is selected when tapped on it CONTEXT: The shoeType UISegmentedControl has 3 segments [City, Running, Baskets] CODE: Here is my code: ViewController.swift : @IBOutlet weak var shoeType: UISegmentedControl! ViewControllerUITest.swift: func testSegmentedControl_WhenTapped_ChangeSegment() { app.launch() let shoeTypeSegmentedControl = app.segmentedControls["city"] app.segmentedControls["city"].tap() XCTAssertEqual(shoeTypeSegmentedControl.label, "City") }
Posted Last updated
.
Post not yet marked as solved
8 Replies
3.7k Views
On an iOS device, using the native keyboard (US english and "Predictive" turned on), if you write eg:"Have a " (with a space at the end)It will suggest three contextually relevant next-word-predictions on the bar at the top of the keyboard:good great niceI want to make use of this next-word prediction logic on iOS, but it turns out that I can only get it to work on OS X, where it's super simple.So here is a tiny command line app that does exactly what I want (allthough only on OS X):import AppKit let str = "Have a " let rangeForEndOfStr = NSMakeRange(str.utf16.count, 0) let spellChecker = NSSpellChecker.sharedSpellChecker() let completions = spellChecker.completionsForPartialWordRange( rangeForEndOfStr, inString: str, language: "en", inSpellDocumentWithTag: 0) print(completions)Running that program will print:Optional(["good", "great", "nice", "lot", "problem", "new", "feeling", "chance", "few", "wonderful", "look", "big", "boyfriend", "better", "very", "job", "bad", "lovely", "crush", "blessed"])Note that the first three words are exactly the same as those displayed by the native (predictive) iOS keyboard. So it works (at least on OS X)!(It works by giving .completionsForPartialWordRange an zero-length range located at the end of the string (where the next word would go), rather than a range containing a partial word, allthough I guess you could say that a non-existing word is also a partial word.)But trying the same approach on iOS (using UITextChecker instead of NSSpellChecker, etc.) does not work:let str = "Have a " let rangeForEndOfStr = NSMakeRange(str.utf16.count, 0) let spellChecker = UITextChecker() print(UITextChecker.availableLanguages()) let completions = spellChecker.completionsForPartialWordRange( rangeForEndOfStr, inString: str, language: "en_US") // ( &lt;-- .availableLanguages() says "en_US" on iOS and "en" on OS X. ) print(completions)(this code can be put in the viewDidLoad of the ViewController of an otherwise empty Single View iOS app.)Run the iOS app and it will just print nil. : (Turns out that UITextChecker's .completionsForPartialWordRange (contrary to NSSpellChecker's) simply returns nil if the range has zero length. I have tried all day to find any other way to get next-word-of-sentence-predictions/-suggestions/-completions on iOS but failed.(NOTE: I have no problem getting UITextChecker to return completions of partially entered wods, ie where the range is not empty, but contains partially written word(prefixe)s, allthough the resulting completions are not sorted so that the more probable comes first, as the documentation says. They are actually just sorted alphabetically ... Anyway, what I want is something else: Given a partially written sentence containing only complete words, I want a list of probable-next-word-in-sentence-completions, exactly as examplified by my OS X example and the native iOS keyboard above.)So, how do I write a working iOS-version of the OS X example above?
Posted
by Jens.
Last updated
.
Post not yet marked as solved
3 Replies
1.8k Views
I have a constraint on my `UIImageView` that is being broken, but I don't understand why. It appears that it is due to the `estimated` item size on my collection view's compositional layout. Any thoughts would be greatly appreciated.Note: code formatting appears to be messed up after pasting, apologies for that.Cell and Layout Section Definition// // PostCell.swift // // Created by Sam Jackson on 10/13/19. // Copyright © 2019 Vita. All rights reserved. // import UIKit import Logging import Kingfisher import Foundation // MARK: PostCell class PostCell: UICollectionViewCell { static let reuseIdentifier = "PostCell" static let authorPhotoSize: CGFloat = 64.0 /// The post that drives the content of this `UICollectionViewCell`. When this /// property is set, the content of the cell will change. var post: Post! { didSet { displayNameLabel.text = post.author.displayName metadataLabel.text = "This is a test." authorPhotoImageView.kf.setImage(with: post.author.photoURL) } } /// Display name of the post author. var displayNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.systemFont(ofSize: 20, weight: .medium) label.textColor = .label return label }() /// Typically shows the timestamp for the post. var metadataLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .gray return label }() /// Profile photo of the post author. var authorPhotoImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.cornerRadius = PostCell.authorPhotoSize / 2 imageView.clipsToBounds = true return imageView }() /// This `UIStackView` organizes the labels in the post header. Specifically, it arranges /// the `displayNameLabel` and `metadataLabel` in a vertical stack. lazy var headerLabelStack: UIStackView = { let stack = UIStackView( arrangedSubviews: [displayNameLabel, metadataLabel] ) stack.translatesAutoresizingMaskIntoConstraints = false stack.axis = .vertical return stack }() /// This `UIStackView` composes the different elements of the post header. Specifically, /// it arranges the `authorPhotoImageView` and `headerLabelStack` in a horizontal stack. lazy var headerStack: UIStackView = { let stack = UIStackView( arrangedSubviews: [authorPhotoImageView, headerLabelStack] ) stack.translatesAutoresizingMaskIntoConstraints = false stack.alignment = .center stack.axis = .horizontal stack.spacing = 8 return stack }() /// This is the all-encompassing stack for a `Post`. By default, it comprises of a header and footer. /// It can be configured to contain different elements of a post, such as a photo or video. lazy var postStack: UIStackView = { let stack = UIStackView( arrangedSubviews: [headerStack] ) stack.translatesAutoresizingMaskIntoConstraints = false stack.axis = .vertical stack.spacing = 8 return stack }() /// Update the data presented in the cell with some `Post`. func configure(with post: Post) { self.post = post } override init(frame: CGRect) { super.init(frame: frame) // All other subviews are managed by stacks. contentView.addSubview(postStack) // Activate all necessary constraints. NSLayoutConstraint.activate([ authorPhotoImageView.heightAnchor.constraint(equalToConstant: PostCell.authorPhotoSize), authorPhotoImageView.widthAnchor.constraint(equalToConstant: PostCell.authorPhotoSize), postStack.topAnchor.constraint(equalTo: contentView.topAnchor), postStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), postStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), contentView.bottomAnchor.constraint(equalTo: postStack.bottomAnchor) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: DefinesLayoutSection extension PostCell { /// Because all posts will be presented the same way within a hosting `UICollectionView`, /// we statically define their layout section here. static func getLayoutSection(withDivider: Bool = false) -&gt; NSCollectionLayoutSection { // Each cell should span the width of the collection view. // The height of the cell should be dynamic. let item = NSCollectionLayoutItem( layoutSize: NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44.0) ) ) // We aren't doing anything with groups at this time, so we leave // these settings the same as those for the `NSCollectionLayoutItem`. let groupSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44.0) ) let group = NSCollectionLayoutGroup.vertical( layoutSize: groupSize, subitem: item, count: 1 ) // Insets for the section should match our other sections. let section = NSCollectionLayoutSection(group: group) section.contentInsets = NSDirectionalEdgeInsets( top: 0, leading: 17, bottom: 0, trailing: 17 ) // Space between cells. section.interGroupSpacing = 17.0 return section } }Console Output2019-10-13 21:03:41.424629-0400 [6217:1241993] [LayoutConstraints] 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) ( "&lt;NSAutoresizingMaskLayoutConstraint:0x28312fb60 h=--&amp; v=--&amp; UIView:0x10c7bef60.height == 44 (active)&gt;", "&lt;NSLayoutConstraint:0x28312caf0 UIImageView:0x10c7beda0.height == 64 (active)&gt;", "&lt;NSLayoutConstraint:0x28312cb90 V:|-(0)-[UIStackView:0x10c7bf580] (active, names: '|':UIView:0x10c7bef60 )&gt;", "&lt;NSLayoutConstraint:0x28312cc80 V:[UIStackView:0x10c7bf580]-(0)-| (active, names: '|':UIView:0x10c7bef60 )&gt;", "&lt;NSLayoutConstraint:0x28312f7a0 'UISV-canvas-connection' UIStackView:0x10c7bf400.top == _UILayoutSpacer:0x282d663a0'UISV-alignment-spanner'.top (active)&gt;", "&lt;NSLayoutConstraint:0x28312f840 'UISV-canvas-connection' UIStackView:0x10c7bf400.centerY == UIImageView:0x10c7beda0.centerY (active)&gt;", "&lt;NSLayoutConstraint:0x28312f930 'UISV-canvas-connection' UIStackView:0x10c7bf580.top == UIStackView:0x10c7bf400.top (active)&gt;", "&lt;NSLayoutConstraint:0x28312f980 'UISV-canvas-connection' V:[UIStackView:0x10c7bf400]-(0)-| (active, names: '|':UIStackView:0x10c7bf580 )&gt;", "&lt;NSLayoutConstraint:0x28312f610 'UISV-spanning-boundary' _UILayoutSpacer:0x282d663a0'UISV-alignment-spanner'.top &lt;= UIImageView:0x10c7beda0.top (active)&gt;" ) Will attempt to recover by breaking constraint &lt;NSLayoutConstraint:0x28312caf0 UIImageView:0x10c7beda0.height == 64 (active)&gt; Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in &lt;UIKitCore/UIView.h&gt; may also be helpful.
Posted
by sroth.
Last updated
.
Post not yet marked as solved
7 Replies
1.6k Views
I have a simple UIKit application that has a UITextView in a UICollectionViewCell. The app is designed for iOS/iPadOS and works just fine on those platforms. However, when run on Mac (Designed for iPad) as soon as I start scrolling the collectionview, the cpu usage spikes to ~85% and stays there indefinitely. The only way to lower the cpu is to click outside of the application window, but once it comes to the foreground again, the cpu usage jumps right back up. I've tried running on Mac in Catalyst mode too, but the same problem occurs with slightly less cpu usage (~45%). Additionally the debugger constantly spits out [API] cannot add handler to 3 from 3 - dropping while scrolling. Does anyone have an explanation or solutions for this? I’m using Xcode Version 14.1 (14B47b) on macOS Ventura 13.0 (22A380). class ViewController: UIViewController { var dataSource: UICollectionViewDiffableDataSource<Section, String>! = nil var collectionView: UICollectionView! = nil var items = Array(0...100).map{"Item \($0)"} enum Section: String { case main } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "List" configureCollectionView() configureDataSource() applyInitialSnapshot() } private func createLayout() -> UICollectionViewLayout { return UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in let size = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100)) let item = NSCollectionLayoutItem(layoutSize: size) let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item]) return NSCollectionLayoutSection(group: group) } } private func configureCollectionView() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.backgroundColor = .systemBackground view.addSubview(collectionView) } private func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration<TestCell, String> { (cell, indexPath, item) in cell.configure(title: item, row: indexPath.item) } dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) { (collectionView, indexPath, identifier) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier) } } private func applyInitialSnapshot() { var snapshot = NSDiffableDataSourceSnapshot<Section, String>() snapshot.appendSections([.main]) snapshot.appendItems(items) dataSource.apply(snapshot, animatingDifferences: false) } } class TestCell: UICollectionViewCell { private let annotationsTextView = UITextView() override init(frame: CGRect) { super.init(frame: frame) addViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(title: String, row: Int) { annotationsTextView.attributedText = .init(string: "Row: \(row) Item: \(title)", attributes: [.font: UIFont.preferredFont(forTextStyle: .title1)]) } private func addViews() { annotationsTextView.isScrollEnabled = false annotationsTextView.isEditable = false annotationsTextView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(annotationsTextView) NSLayoutConstraint.activate([ annotationsTextView.topAnchor.constraint(equalTo: contentView.topAnchor), annotationsTextView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), annotationsTextView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), annotationsTextView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), ]) } }
Posted
by rspoon3.
Last updated
.
Post not yet marked as solved
1 Replies
46 Views
I'm trying to create a dynamic menu on Mac Catalyst. Using a UIBarButtonitem like so to make a "pull down" button: UIDeferredMenuElement *deferredmenuElement; deferredmenuElement = [UIDeferredMenuElement elementWithUncachedProvider:^(void (^ _Nonnull completion)(NSArray<UIMenuElement *> * _Nonnull)) { UIAction *actionOne = [UIAction actionWithTitle:@"Action One" image:nil identifier:nil handler:^(__kindof UIAction * _Nonnull action) { NSLog(@"action one fired."); }]; UIAction *actionTwo = [UIAction actionWithTitle:@"Action Two" image:nil identifier:nil handler:^(__kindof UIAction * _Nonnull action) { NSLog(@"action two fired."); }]; UIAction *actionThree = [UIAction actionWithTitle:@"Action Three" image:nil identifier:nil handler:^(__kindof UIAction * _Nonnull action) { NSLog(@"action three fired."); }]; completion(@[actionOne,actionTwo,actionThree]); }]; UIMenu *wrappedMenu = [UIMenu menuWithChildren:@[deferredmenuElement]]; UIBarButtonItem *uiBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:nil menu:wrappedMenu]; uiBarButtonItem.image = [UIImage systemImageNamed:@"rectangle.and.pencil.and.ellipsis"]; self.navigationItem.rightBarButtonItems = @[uiBarButtonItem]; The button appears in the toolbar but when I click it to expose the menu I get a menu with on element in it that says "Loading...". The the uncached provider block is never called. Running Ventura 13.2.1 and Xcode 14.2.
Posted Last updated
.
Post marked as solved
3 Replies
503 Views
I've implemented an emoji "quick reaction" feature for our messaging feature within our app (using Swift). The reaction UI/UX is supposed to match that of the quick emoji reaction via long press gesture in iMessage almost exactly, aside from which reactions we chose to display. We've implemented this feature using the func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration ...). Within this delegate function we create a container view that has a snapshot of the message TableViewCell with the reaction UIView inserted right above the snapshot, like it does visually in iMessage. This container is passed in to the UITargetedPreview(view: /*here*/, parameters: parameters, target: previewTarget) constructor and is then returned for the aforementioned delegate function. This works functionally, but here are some issues with this UI/UX wise that is different than iMessage, which I will describe: When the user "long presses" to trigger the ContextMenu, it reacts to the press very quickly, i.e duration of fingertip "pressing" is short as ~0.25 seconds, where as a traditional UIGestureRecognizer takes longer than ~1.0 seconds. We'd like to make the required duration of physical "pressing" to be more around 0.5 - 1.0 seconds like in iMessage. When the user initiates the ContextMenu within iMessage, the reactions view and the ContextMenu appear at the same exact time. In our implementation, presuming because the cell snapshot and reaction view are within the same container, they both appear prior to the context menu. The reason why this happens makes sense to me, however I would like to know how iMessage implements the Context Menu functionality in iMessage, such that the reaction view appears with the Context Menu. The user seeing only the message first, then both menu elements. Note: We use the UITargetedPreview so that we can specify a .clear background color for the targetView, as the same UI/UX as in iMessage. We did not find another way to implement that design. In conclusion, in what way does iMessage present Context Menu's such that the the following feature requirements are fullfilled: Background is clear between the reaction view, the message, and the context menu. The duration of gesture press that is required to trigger the menu being more than ~0.5 seconds. As well as the message cell appearing first, and then subsequently the reaction view + context menu together?
Posted Last updated
.
Post marked as solved
2 Replies
85 Views
GOAL: I'm currently unit testing the behavior of my UISwitch when it is pressed. ISSUE: My issue I that the sendActions(for: .valueChanged) that I use to programmatically change the UISwitch's state is not working as I imagined. It doesn't make it change from false to true (in my example). WHAT DID I DO ?: I'm using the following path: I declared my UISwitch as true I used sendActions(for: .valueChanged) for changing it to false I finally used XCTAssertEqual() to check if it correctly equal to false as expected. (I also could have used XCTAssertFalse() to check directly if it was false. Ps: I correctly passed loadViewIfNeeded() in my setUPWithError() QUESTION: How can I test my UISwitch ?? Maybe using UI Tests ? CODE: Here is my code: var sut: ViewController! override func setUpWithError() throws { super.setUp() let storyboard = UIStoryboard(name: "Main", bundle: nil) sut = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController sut.loadViewIfNeeded() } func testGenderButton_ShouldUpdateValueWhenPressed() { sut.genderSwitch.isOn = true sut.genderSwitch.sendActions(for: .valueChanged) XCTAssertEqual(sut.genderSwitch.isOn, false, "\(sut.genderSwitch.isOn) should be equal to false") }
Posted Last updated
.
Post not yet marked as solved
1 Replies
369 Views
I've encountered a bug shown as [Assert] UINavigationBar decoded as unlocked for UINavigationController, or navigationBar delegate set up incorrectly. Inconsistent configuration may cause problems. navigationController=<UINavigationController: 0x13800ca00>, navigationBar=<UINavigationBar: 0x137108540; frame = (0 59; 0 50); opaque = NO; autoresize = W; layer = <CALayer: 0x600002d3dd40>> delegate=0x13800ca00 This bug appears right after the IOS16.0 Update. And this bug doesn't allow me to access the next view controller when I click the button in the navigation bar on the root view controller. and I checked segue iditifier and named it, didn't work. Also I deleted the view controller that contained the bug and created an exactly same one, didn't work at all. It seems like the problem of source code about storyborad, but i dont't know XML. Is there any way to handle that problem? or it just a regular updating bug of ios? So confused. Thanks Aiden
Posted Last updated
.
Post marked as solved
3 Replies
86 Views
I have a UIStepper with the following parameters: value: 40 minimumValue: 35 maximumValue: 45 I want to update the UILabel (linked to it) at app' launch in order to make the it displays value. It's currently displaying the minimumValue by default and I don't know why. Any ideas ?
Posted Last updated
.