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

UIKit Documentation

Post

Replies

Boosts

Views

Activity

n00b please help button not working
so im a student and im cloning an app just to play around with Swift. I have a view that contains a button that, when pressed, goes to a different view with a sheet presentation. I was to add another button on that sheet view that also goes to another view but full screen. so first view button -> sheet button -> last view the first button works fine, but on the sheet the button won't even print anything to the console when pressed. The first button (that works), was only added programmatically because I had an image in the background of the view with a fake button look, so I did not add a button with a frame or CG. im guessing that is my issue since for the sheet button I am adding the button programmatically and the UI too. this is the code for the button that doesnt work //cashout button cashOutBut.configuration = .filled() cashOutBut.configuration?.baseBackgroundColor = .systemGreen cashOutBut.configuration?.cornerStyle = .large cashOutBut.titleLabel?.text = String("Cash Out") cashOutBut.configuration?.title = String("Cash Out") cashOutBut.isEnabled = true //var config = UIButton.Configuration.filled() //config.baseBackgroundColor = .green view.addSubview(cashOutBut) } @IBAction func cashOutBut(_sender: Any){ let detailViewController = CashOutViewController() let nav = UINavigationController(rootViewController: detailViewController) nav.modalPresentationStyle = .fullScreen (nav, animated: true, completion: nil) } the one that works is not added to the view/subview and is only @IBAction func cashOut(_ sender: Any){ let detailViewController = SheetViewController() let nav = UINavigationController(rootViewController: detailViewController) nav.modalPresentationStyle = .pageSheet if let sheet = nav.sheetPresentationController { sheet.detents = [.medium(), .large()] sheet.prefersScrollingExpandsWhenScrolledToEdge = false sheet.preferredCornerRadius = 25// add sheet.prefersGrabberVisible = true } present(nav, animated: true, completion: nil) } do I need to add a target or someting?
1
0
308
Aug ’23
UIResponder.printContent(_:) is not called when tapping Print in navigation item title menu
By following the documentation, in Info.plist I have added UIApplicationSupportsPrintCommand = true, but when tapping the navigation item's title and selecting Print, printContent(_:) is never called. On the other hand, when selecting Move, move(_:) is called as expected. What's the problem? The issue can be reproduced by using the code below in a newly created Xcode project with the App template. class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "asdf" navigationItem.documentProperties = UIDocumentProperties(url: URL(fileURLWithPath: "/asdf")) navigationItem.titleMenuProvider = { suggestions in return UIMenu(children: suggestions) } } override func move(_ sender: Any?) { print("move") } override func printContent(_ sender: Any?) { print("printContent") } }
0
0
288
Aug ’23
UISplitViewController displays button to change the display mode even when presentsWithGesture = false
I have a document-based app which displays a view controller with a navigation bar (i.e. it's inside a navigation controller) which is also the detail view controller of a split view controller. I'm using this sample code to just show a back button in the navigation bar of the document view controller: class DocumentViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() splitViewController!.presentsWithGesture = false navigationItem.backAction = UIAction(handler: { _ in }) } } In a regular width, this works as expected: only the back button is displayed. In a compact width such as a portrait iPhone, the split view seems to display the navigation bar button to show the master view controller (the one with the icon to the right of the back button, labeled “Root View Controller"). According to the documentation of presentsWithGesture: When this property is false, the split view controller doesn’t install a gesture recognizer for changing the display mode. The split view controller also doesn’t display a button to change the display mode. Is this a bug, or an error in the documentation, or am I doing something wrong?
1
0
386
Aug ’23
Paste Permission Localisation Bug ? Can we override this permission localisation ?
When I am about to access the clipboard, the apple paste permission will prompt and ask for permission. But the localisation seem won't change the language if I change the phone language ? Scenario : If my phone at "English" Language for the first time, the paste permission will prompt in "English" which is correct, but then I switch the phone language to "Spanish", the paste permission prompt still in "English". I need to restart the phone, then only the prompt permission will be appear in "Spanish" language. If I switch back to "English", the prompt still remain in "Spanish" Language until I restart the phone. Any way we can override this in plist like other privacy permission ? Or this is a known bugs ? In iOS 16.6 I will attached the screenshot. Anyone can answer and help on this? Thank you so much.
1
0
704
Aug ’23
Optimizing loading lots of small images in iOS App - My attempt
In my iOS app, I need to load and display lots of small images like icons and thumbnails. This was causing slow loading and high memory usage issues. I tried optimizing by encoding the images to Base64 strings and embedding them directly in code. Here's a Swift code snippet to demonstrate: let imageData = UIImage(named:"image.png")!.pngData()! let base64String = imageData.base64EncodedString() let imgBase64 = "data:image/png;base64,\(base64String)" let image = UIImage(data: Data(base64Encoded: imgBase64)!) This improved the app's performance - loading speed increased by 2x and memory usage decreased by 30%. Way better than loading individual image files! Curious to know if anyone else has tried Base64 image loading? Are there other optimization techniques you'd recommend? I'm interested to learn more approaches to smooth image loading in iOS apps. Btw, this blog post gave me the idea to try Base64 encoding for faster image loading. Recommend checking it out for more techniques! https://itoolkit.co/blog/2023/08/improve-page-speed-and-seo-with-base64-encoding-images/
2
0
617
Aug ’23
Crash on pushViewController with [NSNull set]: unrecognized selector
I have an app where I just created a new, working viewController in a separate project. I copy/pasted the code and xibs (several subviews) into the new project. All compiles fine. Relevant code: `let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) //let nextViewController = storyBoard.instantiateViewController(withIdentifier: "NewManualGlyphVC") as! NewManualPickGlyphViewController //old Selector let nextViewController = storyBoard.instantiateViewController(withIdentifier: "GlyphSelectVC") as! GlyphSelectViewController //new Selector self.navigationController?.pushViewController(nextViewController, animated: true) ` The commented out line was the vector to the old, working VC. The new code crashes inside the push. the new nextViewController is fine, the Xcode quick view shows the expected view, and the navController is also just fine. The reported error is: `myApp[42661:963870] -[NSNull set]: unrecognized selector sent to instance 0x7ff86599bc30 ` Environment is Xcode 14.3.1 compiled to ios13, target device iOS 16. Any thoughts? Thanks!!
3
0
485
Aug ’23
iOS 17 beta6 crashed
xcode15 beta6 iphone 12 pro、iOS 17 beta6 class ViewController: UIViewController { @IBOutlet weak var subView: UIView! @IBOutlet weak var imageView: BFAnimatedImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imageView.layer.setNeedsDisplay() } } class BFAnimatedImageView: UIImageView { override func display(_ layer: CALayer) { super.display(layer) } } console log *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[display.BFAnimatedImageView displayLayer:]: unrecognized selector sent to instance 0x105809b30' *** First throw call stack: (0x18d3635e0 0x1856bbc00 0x18d3f3eec 0x1902a2830 0x18d2a8554 0x18d3e9860 0x104098f08 0x104098f74 0x18e8d3470 0x18e8d98a0 0x18e8d2b90 0x18f7a62d4 0x18d2adb58 0x18d2ac34c 0x18d2aa24c 0x18d2a9e18 0x1ce9675ec 0x18f6b7400 0x18f6b6a3c 0x18f8d9f10 0x104099ad0 0x104099a48 0x104099b4c 0x1afa3fd44) libc++abi: terminating due to uncaught exception of type NSException why crashed.....
2
0
693
Aug ’23
Search bar in navigation bar displayed as icon
Hi, I have a controlled contained in a split view controller primary controller with a UISearchController assigned in navigationItem.searchController. On iPhone the search bar is directly displayed in the navigation bar. This is want I want. But on iPad, the search bar is hidden and a search button is displayed in the top right of the navigation bar. In order to display the search bar the user must click on the icon to display the search bar. I want the search bar to always be visible, like on iPhone. How can I achieve that? This is the code I use to include the UISearchController: let searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false And this is the result on both devices: Thank you
1
0
1.1k
Aug ’23
UICollectionView scrolling control using UICollectionViewCompositionalLayout
Hi 👋 Given I have a UICollectionView using a UICollectionViewCompositionalLayout. The layout contains of a single group containing 3 full-width items. The orthogonalScrollingBehavior behaviour of the section is set to .paging. The section includes a header in which a UISegmentedControl is presented. Here's what I want to achieve: User changes the segmented control: The value change (selectedIndex) of the segmented control alters the presented page in the collection view (currently via scrollToItem(at:at:animated:)). User swipes the paging collection view: When the user swipes the pages, the segmentedControl has to be changed to reflect the current page Here's my problem: When I use the segmented control to navigate through the pages, the sections visibleItemsInvalidationHandler fires and updates the segmented control with (temporary) invalid values. This causes some UI glitches in the segmented control. I can't rely on the UIScrollView delegate because the collection view seems to use a different scroll view for the paging mechanism internally. Question Is there a way to intercept the visibleItemsInvalidationHandler for the time the collection view animates the scrollToItem(at:at:animated:) changes? Or is there any other alternative to the visibleItemsInvalidationHandler which is called only once after the transition is done? Here's my layout setup: private func makeCompositionalLayout() -> UICollectionViewLayout { let itemSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(300) ) let padding: CGFloat = 16 let item = NSCollectionLayoutItem(layoutSize: itemSize) item.contentInsets = NSDirectionalEdgeInsets( top: 0, leading: padding, bottom: 0, trailing: padding ) let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44)) let header = NSCollectionLayoutBoundarySupplementaryItem( layoutSize: headerSize, elementKind: MyCollectionReusableView.sectionHeaderElementKind, alignment: .top ) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(300)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .paging section.visibleItemsInvalidationHandler = { [weak self] _, contentOffset, _ in guard let self, let collectionView else { return } let pageWidth = collectionView.bounds.width let fractionalPage = contentOffset.x / pageWidth segmentedControlDelegate?.update(idx: lround(fractionalPage)) } section.boundarySupplementaryItems = [header] return UICollectionViewCompositionalLayout(section: section) }
0
0
474
Aug ’23
Positioning views: is it me or SwiftUI ?
After more than 2 years of intense use of SwiftUI I appreciate many of its features, particularly the speed at which I can get some code running. But, there are some major buts … Screen Position, I keep struggling with try, test, error and retry to position views relative to each others, withy many iterations to tune the x and y parameters. And preview does not help when view is too complex: I find it more reliable to test in simulator. At the end, my code is messed with .position, .offset, … that I manually adjusted but may break if I change something elsewhere in the body. The fact that position is relative to center of view (different from UIKit) makes it even more mind boggling. For sure, UIKit constraints were not so easy, but you got a very stable code. That's not the case with SwiftUI z position In some cases, I want the View to appear on front of all others. It may be a very simple Rectangle() with overlay, e.g., to mimic an alert. And I struggle with the Rectangle drawn behind another view, even trying to adjust the zIndex to no avail… Should I create an explicit View instead of creating the Rectangle directly in the body ? So am I misusing SwiftUI, or are they points that SwiftUI should improve in the future ?
1
1
597
Aug ’23
Image quality decreases while saving UIImage
We are creating a PDF viewer application fin the Xamarin platform. In that, we are adding a stamp annotation, which is added as a UIImage. While saving this UIImage, there is a loss in the quality of the image annotation. I have attached the example code below that causes the issue. Is there any way to improve the quality of the UIImage that we get from UIImageView? I have attached an image that has been changed from 36kb to 18kb. The image is more pixelated than the initial image. Assembly assembly = Assembly.Load(new AsemblyName("Syncfusion.SfPdfViewer.XForms.iOS")); Stream stream = assembly.GetManifestResourceStream(string.Format("<path>.screen-shot.png")); var imagedata = NSData.FromStream(stream); if (imagedata != null) { image = UIImage.LoadFromData(imagedata); } UIImageView imageView1 = new UIImageView(image); imageView1.Frame = imageView.Bounds; var UiImageTest=ConvertToImage(imageView1); using(var imageStream=UiImageTest.AsPNG().AsStream()) { string path = "/Users/<path on MAC>"; string filepath = System.IO.Path.Combine(path, "StampParserTestjpegSave.png"); FileStream outputFileStream = File.Open(filepath, FileMode.Create); imageStream.Position = 0; imageStream.CopyTo(outputFileStream); outputFileStream.Close(); } private UIImage ConvertToImage(UIView view) { if (UIDevice.CurrentDevice != null && UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { var format = new UIGraphicsImageRendererFormat(); format.Scale = UIScreen.MainScreen.Scale; var renderer = new UIGraphicsImageRenderer(view.Bounds.Size, format); return renderer.CreateImage((rendererContext) => { view.Layer.RenderInContext(rendererContext.CGContext); }); } else { UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, 0); view.Opaque = false; view.DrawViewHierarchy(view.Bounds, true); view.Layer.RenderInContext(UIGraphics.GetCurrentContext()); var img = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return img; } }
3
0
449
Aug ’23
CADisplayLink and UITouch events
Hi. I'm currently working on a project, where I try to achieve the best possible UX when rendering an interactive scene using custom Metal renderer. The problem I'm facing right now is that from what I've observed, the timing of how touch events (in touchesBegan/Moved/Ended/Cancelled) arrive with regards to DisplayLink callbacks is different on different devices using latest stable iOS. Disregarding special cases (fast touches movement causing two touchesMoved along with a single touchedEnded arriving during a frame interval and having awkward timing), the general picture is this: on 14 Pro: vsync - (8 ms of nothing) - touches - vsync on 11 Pro Max: vsync - touches - (16 ms of nothing) - vsync In order to minimize input-to-presentation latency and fit CPU + GPU work into one frame, I'd like to schedule drawing right when CADisplayLink callback arrives. The problem is that at this point on 11 Pro Max I have no knowledge about whether touches arrive or not, so the best we could do is to process those touches and schedule redraw on next vsync, which causes almost two frames latency between input and draw that reflects changes caused by this input (33 ms) On 14 Pro, touches are dispatched just before next vsync, so the actual latency is just one 120hz frame (8ms). What are possible workarounds to achieve the same UX on iPhone 11 Pro Max?
0
1
628
Aug ’23
Table View cell issue
I was working on the to-do list app. I added the prototype cell and its identifier as a cell. but the cells are not showing in the table view while running in the simulator. Can anyone tell me what mistakes I am making? The following is code from the view controller. import UIKit class ViewController: UIViewController { @IBOutlet var tableView : UITableView! let Tasks : [String] = [] override func viewDidLoad() { super.viewDidLoad() } @IBAction func didTapAdd(){ } } extension ViewController : UITextViewDelegate , UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Tasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = Tasks[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath : IndexPath){ tableView.deselectRow(at: indexPath, animated: true) } }
3
0
399
Aug ’23
masksToBounds vs clipsToBounds
What is the difference between clipsToBounds on UIView, and masksToBounds on it’s corresponding CALayer? Is there any? When debugging I see that setting clipsToBounds = true on a UIView, automatically sets masksToBounds = true on the underlying CALayer, and vice versa. From my understanding, UIViews are basically lightweight wrappers around CALayer, so it would make sense that clipsToBounds calls masksToBounds behind the scenes. Is that assumption correct?
1
0
695
Aug ’23
How to detect screenshots on iOS 17 beta?
I am able to detect screenshot only after screenshot is taken. UIApplication.userDidTakeScreenshotNotification. But my requirement is to detect at the same time while user is taking screenshot, so that I can hide my confidential data. Please comment out if there are any better solutions or any callback functions available.
1
0
1.1k
Aug ’23
Swift can't read the textDocumentProxy.documentContextBeforeInput after entering a newline
I am typing string text on textDocumentProxy in a custom keyboard app. The input text includes newlines and punctuation letters, but when I try to edit the textDocumentProxy field, the textDocumentProxy.documentContextBeforeInput in case a newline \n is included, it does not return full content before input. I placed the cursor on after the good morning word center, I got only good string text. The remaining "hi folks", words do not return. Here are some examples I have tried. var inputText = "Hi folks, Good morning to everyone " var txtBeforeCursor = textDocumentProxy.documentContextBeforeInput ?? "" print("Before Cursor text : ",txtBeforeCursor) Output is: Before Cursor text : Good
0
0
578
Aug ’23