At this line of code (SketchTextSelectionManager.swift:449), sometimes there will be crashes based on crashlytics reports.
let selection = pdfPage.selectionForWord(at: location)
This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selectionforword(at:)
Attached the full stacktrace:
Crashed: com.apple.root.user-initiated-qos.cooperative
0 CoreGraphics 0x30c968 PageLayout::getWordRange(unsigned long, long) const + 908
1 CoreGraphics 0x30bbc0 PageLayout::getTextRangeIndex(CGPoint, CGPDFSelectionType, SelectionPrecision) const + 2292
2 CoreGraphics 0x44a53c CGPDFSelectionCreateBetweenPointsWithOptions + 384
3 PDFKit 0x8d5f8 -[PDFPage selectionFromPoint:toPoint:type:] + 168
4 PDFKit 0x92040 -[PDFPage _rvItemAtPoint:] + 64
5 PDFKit 0x91f4c -[PDFPage rvItemAtPoint:] + 84
6 PDFKit 0x8caa8 -[PDFPage selectionForWordAtPoint:] + 40
7 MyApp 0x8420e0 closure #1 in SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 449 (SketchTextSelectionManager.swift:449)
8 MyApp 0x841a70 SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 205 (CurrentNoteManager.swift:205)
9 libswift_Concurrency.dylib 0x61104 swift::runJobInEstablishedExecutorContext(swift::Job*) + 252
10 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480
11 libswift_Concurrency.dylib 0x611c4 swift::runJobInEstablishedExecutorContext(swift::Job*) + 444
12 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144
13 libdispatch.dylib 0x15d8c _dispatch_root_queue_drain + 392
14 libdispatch.dylib 0x16590 _dispatch_worker_thread2 + 156
15 libsystem_pthread.dylib 0x4c40 _pthread_wqthread + 228
16 libsystem_pthread.dylib 0x1488 start_wqthread + 8
```
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
In the header for UIViewController, the method dismissViewControllerAnimated is declared like this:
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion NS_SWIFT_DISABLE_ASYNC API_AVAILABLE(ios(5.0));
NS_SWIFT_DISABLE_ASYNC means that there's no async version exposed like there would normally be of a method that exposes a completion handler. Why is this? And is it unwise / unsafe for me to make my own async version of it using a continuation?
My use case is that I want a method that will sequentially dismiss all view controllers presented by a root view controller. So I could have this extension on UIViewController:
extension UIViewController {
func dismissAsync(animated: Bool) async {
await withCheckedContinuation { continuation in
self.dismiss(animated: animated) {
continuation.resume()
}
}
}
func dismissPresentedViewControllers() async {
while self.topPresentedViewController != self {
await self.topPresentedViewController.dismissAsync(animated: true)
}
}
var topPresentedViewController: UIViewController {
var result = self
while result.presentedViewController != nil {
result = result.presentedViewController!
}
return result
}
With "Requires full screen" Split View and Slide Over are disabled but the line on the bottom of the screen remains.
How can that line removed as when a video is displayed full screen?
Topic:
UI Frameworks
SubTopic:
General
As can be seen in the screenshot attached, I can not see the options in this window. A prompt window before this also did not show any buttons in the visible space. However, I made a guess and could get to this window by clicking on what I think was "Ok" or something similar.
But on this I could not do any action and had to force quit the app.
The SwiftUI Playground code below demonstrates that a .jpeg image can be read and written to the iOS file system. While, a.png image can only be read; the writing request appears to be ignored. Can anyone please tell me how to code to save a .png image using SwiftUI to the iOS file system.
Code:
import SwiftUI
import UniformTypeIdentifiers
/*
(Copied from Playground 'Help' menu popup.)
UIImage Summary
An object that manages image data in your app.
You use image objects to represent image data of all kinds, and the UIImage class is capable of managing data for all image formats supported by the underlying platform. Image objects are immutable, so you always create them from existing image data, such as an image file on disk or programmatically created image data. An image object may contain a single image or a sequence of images for use in an animation.
You can use image objects in several different ways:
Assign an image to a UIImageView object to display the image in your interface.
Use an image to customize system controls such as buttons, sliders, and segmented controls.
Draw an image directly into a view or other graphics context.
Pass an image to other APIs that might require image data.
Although image objects support all platform-native image formats, it’s recommended that you use PNG or JPEG files for most images in your app. Image objects are optimized for reading and displaying both formats, and those formats offer better performance than most other image formats. Because the PNG format is lossless, it’s especially recommended for the images you use in your app’s interface.
Declaration
class UIImage : NSObject
UIImage Class Reference
*/
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ImageFileDoc: FileDocument {
static var readableContentTypes = [UTType.jpeg, UTType.png]
static var writableContentTypes = [UTType.jpeg, UTType.png]
var someUIImage: UIImage = UIImage()
init(initialImage: UIImage = UIImage()) {
self.someUIImage = initialImage
}
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let some = UIImage(data: data)
else {
throw CocoaError(.fileReadCorruptFile)
}
self.someUIImage = some
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
switch configuration.contentType {
case UTType.png:
if let data = self.someUIImage.pngData() {
return .init(regularFileWithContents: data)
}
case UTType.jpeg:
if let data = self.someUIImage.jpegData(compressionQuality: 1.0) {
return .init(regularFileWithContents: data)
}
default:
break
}
throw CocoaError(.fileWriteUnknown)
}
}
struct ContentView: View {
@State private var showingExporterPNG = false
@State private var showingExporterJPG = false
@State private var showingImporter = false
@State var message = "Hello, World!"
@State var document: ImageFileDoc = ImageFileDoc()
@State var documentExtension = ""
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text(message)
Button("export") {
if documentExtension == "png" {
message += ", showingExporterPNG is true."
showingExporterPNG = true
}
if documentExtension == "jpeg" {
message += ", showingExporterJPG is true."
showingExporterJPG = true
}
}
.padding(20)
.border(.white, width: 2.0)
.disabled(documentExtension == "")
Button("import") {
showingImporter = true
}
.padding(20)
.border(.white, width: 2.0)
Image(uiImage: document.someUIImage)
.resizable()
.padding()
.frame(width: 300, height: 300)
}
// exporter .png
.fileExporter(isPresented: $showingExporterPNG, document: document, contentType: UTType.png) { result in
switch result {
case .success(let url):
message += ", .\(documentExtension) Saved to \(url.lastPathComponent)"
case .failure(let error):
message += ", Some error saving file: " + error.localizedDescription
}
}
// exporter .jpeg
.fileExporter(isPresented: $showingExporterJPG, document: document, contentType: UTType.jpeg) { result in
switch result {
case .success(let url):
message += ", .\(documentExtension) Saved to \(url.lastPathComponent)"
case .failure(let error):
message += ", Some error saving file: " + error.localizedDescription
}
}
// importer
.fileImporter(isPresented: $showingImporter, allowedContentTypes: [.png, .jpeg]) { result in
switch result {
case .failure(let error):
message += ", Some error reading file: " + error.localizedDescription
case .success(let url):
let gotAccess = url.startAccessingSecurityScopedResource()
if !gotAccess {
message += ", Unable to Access \(url.lastPathComponent)"
return
}
documentExtension = url.pathExtension
guard let fileContents = try? Data(contentsOf: url)
else {
message += ",\n\nUnable to read file: \(url.lastPathComponent)\n\n"
url.stopAccessingSecurityScopedResource()
return
}
url.stopAccessingSecurityScopedResource()
message += ", Read file: \(url.lastPathComponent)"
message += ", path extension is '\(documentExtension)'."
if let uiImage = UIImage(data: fileContents) {
self.document.someUIImage = uiImage
}else{
message += ", File Content is not an Image."
}
}
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags:
Files and Storage
Developer Tools
iPad
Swift Playground
When I use the following code
List {
ForEach(data.items, id: \.knowledgeInfo.mediaID) { item in
SelectableKnowledgeListItem(knowledgeData: item, baseID: data.knowledgeBaseID, isSelectionMode: $isSelectionMode, selectedItems: $selectedItems)
.KnowledgeListItemStyle()
}
// 添加底部加载更多
if !data.isEnd && !isRefreshing {
ProgressView()
.frame(maxWidth: .infinity, alignment: .center)
.onAppear {
self.isRefreshing = true
manager.getKnowledgeList(knowledgeBaseID: data.knowledgeBaseID, completion: {
self.isRefreshing = false
})
}
}
}
.animation(.interactiveSpring)
.scrollContentBackground(.hidden)
.environment(\.defaultMinListHeaderHeight, 7)
The number of Views rendered in the List remains unchanged after he adds an item to data.items (data is an ObservedObject, items is Published) at runtime.When I removed .animation(.interactiveSpring), it would be processed normally.And if I perform a delete operation after adding, it will cause a crash.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (11) must be equal to the number of sections contained in the collection view before the update (10), plus or minus the number of sections inserted or deleted (1 inserted, 1 deleted).
Topic:
UI Frameworks
SubTopic:
SwiftUI
When my iOS app runs on macOS in "designed for iPad" mode, the system foreground colour RGBA values seem strange.
Looking at [UIColor labelColor], [UIColor secondaryLabelColor] etc. on iOS, I see values like these: (Light Mode)
// R G B A
fg0 = 0 0 0 255
fg1 = 10 10 13 153
fg2 = 10 10 13 76
fg3 = 10 10 13 45
Note in particular that fg0, aka labelColor, is solid black.
When I run it on my Mac, the values I see are:
// R G B A
fg0 = 0 0 0 216
fg1 = 0 0 0 127
fg2 = 0 0 0 66
fg3 = 0 0 0 25
Here, fg0 has alpha = 216.
The result is that it looks like a dark grey, on a white background.
Of course it's reasonable for macOS to have a different colour palette than iOS - but native macOS apps seem to have solid 100% black as their foreground colour.
Do others see this? What should I be doing?
Note that I'm getting colour values using UIColor's getRed: blue: green: alpha: method and then using these colour values for some custom GPU drawing. Previously I was using solid black and white, but at some point I updated it to use UIColor in order to respond to light/dark-mode changes.
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now.
The FoodTruckModel adds new Order values with an animation:
// FoodTruckModel.swift
withAnimation(.spring(response: 0.4, dampingFraction: 1)) {
self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator))
}
This then animates the OrdersTable when new Order values are added.
Here is a small change to OrdersTable:
// OrdersTable.swift
- @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)]
+ @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)]
Running the app now inserts new Order values at the top.
The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top:
What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation.
Scrolling the Table fixes the animation.
Changing the creationData sort order from reverse to forward and back to reverse fixes the animation.
Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
I'm developing a grid of focusable elements in SwiftUI with different sizes for tvOS (similar to a tv channel grid).
Because the Focus Engine calculates the next view to focus based on the center of the currently focused view, sometimes it changes focus to an unexpected view. Here's an example:
Actual:
Expected:
Is it possible to customize the anchor point from which the focus engine traces a ray to the next view? I would prefer the leading edge in my case.
In order to make referencing keys for localized strings a little more reliable, our application references generated constants for localized string keys:
This eliminates the potential for developers to misspell a key when referencing a localized strings. And because these constants are automatically generated by the exact same process that provides localized strings for the application, each and every constant is guaranteed to have a localized string associated with it.
I’m currently attempting to implement something similar for the localized strings referenced by our new App Intents. Our initial release of App Intent functionality is simply using string literals to reference localized strings:
However, I am running into several issues when trying to reference the string keys as a constant. The closest I managed to get was defining the constant as either a LocalizationValue or as a StaticString and referencing the constant while initializing the LocalizedStringResource. With this approach, I see no errors from Xcode until I try and compile. What’s more is that the wording of the error being thrown is quite peculiar:
As you can see with the sample code above, I am clearly calling LocalizedStringResource’s initializer directly as Indicated by the error.
Is what I’m trying to do even possible with App Intents? From my research, it does look like iOS app localization is moving more towards using string literals for localized strings. Like with String Catalog’s ability to automatically generate entries from strings referenced in UI without the need for a key. However, we’d prefer to use constants if possible for the reasons listed above.
I'm encountering an issue displaying a large HTML string (over 11470 characters) in a UILabel. Specifically, the Arabic text within the string is rendering left-to-right instead of the correct right-to-left direction. I've provided a truncated version of the HTML string and the relevant code snippet below. I've tried setting the UILabel's text alignment to right, but this didn't resolve the issue. Could you please advise on how to resolve this bidirectional text rendering problem?
The results of the correct and incorrect approaches are shown in the image below.
Here's the relevant Swift code:
let labelView: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.semanticContentAttribute = .forceRightToLeft
label.backgroundColor = .white
label.lineBreakMode = .byWordWrapping
return label
}()
//Important!!
//It must exceed 11470 characters.
let htmlString = """
<p style=\"text-align: center;\"><strong>İSTİÂZE</strong></p> <p>Nahl sûresindeki:</p>
<p dir="rtl" lang="ar"> فَاِذَا قَرَاْتَ الْقُرْاٰنَ فَاسْتَعِذْ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ </p>
<p><strong>“</strong><strong>Kur’an okuyacağın zaman kovulmuş şeytandan hemen Allah’a sığın!</strong><strong>”</strong> (Nahl 16/98) emri gereğince Kur’ân-ı Kerîm okumaya başlarken:</p> <p dir="rtl" lang="ar">اَعُوذُ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ</p> <p><em>“Kovulmuş şeytandan Allah’a sığınırım” </em>deriz. Bu sözü söylemeye “istiâze<em>” denilir. “Eûzü”</em>, sığınırım, emân dilerim, yardım taleb ederim, gibi anlamlara gelir. It must exceed 11470 characters.</p>
“””
if let data = htmlString.data(using: .utf8) {
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
do {
let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil)
labelView.attributedText = attributedString
} catch {
print("HTML string işlenirken hata oluştu: \(error)")
}
}
I'm using iOS 18.2 and Swift 6. Any suggestions on how to correct the bidirectional text rendering?
Hello,
is there a way to implement Continuity Markup in our own apps?
(This is what I'm talking about: https://support.apple.com/en-us/102269 , scroll down to "Use Continuity Markup").
Also, why does a QuickLook panel (QLPreviewPanel.shared()) not display the markup options when triggered from my app for png image files in my app's Group Container? Do I need to implement certain NSServicesMenuRequestor methods for that?
Sadly, I could not find any docs on that.
Thank you,
– Matthias
I want use SensorKit data for research purposes in my current app.
I have applied for and received permission from Apple to access SensorKit Data. I have granting all the necessary permissions. But no data retrieved.
I am using didCompleteFetch for retrieving data from Sensorkit. CompleteFetch method calls but find the data. Below is my SensorKitManager Code.
import SensorKit
import Foundation
protocol SensorManagerDelegate: AnyObject {
func didFetchPhoneUsageReport(_ reports: [SRPhoneUsageReport])
func didFetchAmbientLightSensorData(_ data: [SRAmbientLightSample])
func didFailFetchingData(error: Error)
}
class SensorManager: NSObject, SRSensorReaderDelegate {
private let phoneUsageReader: SRSensorReader
private let ambientLightReader: SRSensorReader
weak var delegate: SensorManagerDelegate?
override init() {
self.phoneUsageReader = SRSensorReader(sensor: .phoneUsageReport)
self.ambientLightReader = SRSensorReader(sensor: .ambientLightSensor)
super.init()
self.phoneUsageReader.delegate = self
self.ambientLightReader.delegate = self
}
func requestAuthorization() {
let sensors: Set<SRSensor> = [.phoneUsageReport, .ambientLightSensor]
guard phoneUsageReader.authorizationStatus != .authorized || ambientLightReader.authorizationStatus != .authorized else {
log("Already authorized. Fetching data directly...")
fetchSensorData()
return
}
SRSensorReader.requestAuthorization(sensors: sensors) { [weak self] error in
DispatchQueue.main.async {
if let error = error {
self?.log("Authorization failed: \(error.localizedDescription)", isError: true)
self?.delegate?.didFailFetchingData(error: error)
} else {
self?.log("Authorization granted.")
self?.fetchSensorData()
}
}
}
}
func fetchSensorData() {
guard let fromDate = Calendar.current.date(byAdding: .day, value: -1, to: Date()) else {
log("Failed to calculate 'from' date.", isError: true)
return
}
let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: fromDate.timeIntervalSinceReferenceDate)
let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate)
let phoneUsageRequest = SRFetchRequest()
phoneUsageRequest.from = fromTime
phoneUsageRequest.to = toTime
phoneUsageRequest.device = SRDevice.current
let ambientLightRequest = SRFetchRequest()
ambientLightRequest.from = fromTime
ambientLightRequest.to = toTime
ambientLightRequest.device = SRDevice.current
phoneUsageReader.fetch(phoneUsageRequest)
ambientLightReader.fetch(ambientLightRequest)
}
// ✅ Delegate Methods
func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) {
Task.detached {
if reader.sensor == .phoneUsageReport {
if let samples = reader.fetch(fetchRequest) as? [SRPhoneUsageReport] {
DispatchQueue.main.async { [weak self] in
self?.delegate?.didFetchPhoneUsageReport(samples)
}
}
} else if reader.sensor == .ambientLightSensor {
if let samples = reader.fetch(fetchRequest) as? [SRAmbientLightSample] {
DispatchQueue.main.async { [weak self] in
self?.delegate?.didFetchAmbientLightSensorData(samples)
}
}
}
}
}
func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool {
return true
}
func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, failedWithError error: any Error) {
DispatchQueue.main.async { [weak self] in
self?.delegate?.didFailFetchingData(error: error)
}
}
// MARK: - Logging Helper
private func log(_ message: String, isError: Bool = false) {
if isError {
print("❌ [SensorManager] \(message)")
} else {
print("✅ [SensorManager] \(message)")
}
}
}
And ViewController
import UIKit
import SensorKit
class ViewController: UIViewController {
private var sensorManager: SensorManager!
override func viewDidLoad() {
super.viewDidLoad()
setupSensorManager()
}
private func setupSensorManager() {
sensorManager = SensorManager()
sensorManager.delegate = self
sensorManager.requestAuthorization()
}
}
// MARK: - SensorManagerDelegate
extension ViewController: SensorManagerDelegate {
func didFetchPhoneUsageReport(_ reports: [SRPhoneUsageReport]) {
for report in reports {
print("Total Calls: (report.totalOutgoingCalls + report.totalIncomingCalls)")
print("Outgoing Calls: (report.totalOutgoingCalls)")
print("Incoming Calls: (report.totalIncomingCalls)")
print("Total Call Duration: (report.totalPhoneCallDuration) seconds")
}
}
func didFetchAmbientLightSensorData(_ data: [SRAmbientLightSample]) {
for sample in data {
print(sample)
}
}
func didFailFetchingData(error: Error) {
print("Failed to fetch data: \(error.localizedDescription)")
}
}
Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated.
I want record screen in my app,the method startCaptureWithHandler:completionHandler:,the sampleBuffer, It is supposed to exist but it has become nil.Not only that,but there‘s another problem,when I want to stop recording and save the video,I will check [RPScreenRecorder sharedRecorder].recording first, it will be false sometime,that problems are unusual in iOS 18.3.2 iPhoneXs Max,and unexpected,here is my code
-(void)startCaptureScreen {
NSLog(@"AKA++ startCaptureScreen");
if ([[RPScreenRecorder sharedRecorder] isRecording]) {
return;
}
//屏幕录制
[[RPScreenRecorder sharedRecorder]setMicrophoneEnabled:YES];
NSLog(@"AKA++ MicrophoneEnabled AAAA startCaptureScreen");
[[RPScreenRecorder sharedRecorder]setCameraEnabled:YES];
[[RPScreenRecorder sharedRecorder] startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
if(self.assetWriter == nil){
if (self.AVAssetWriterStatus == 0) {
[self setupAssetWriterAndStartWith:sampleBuffer];
}
}
if (self.AVAssetWriterStatus != 2) {
return;
}
if (error) {
// deal with error
return;
}
if (self.assetWriter.status != AVAssetWriterStatusWriting) {
[self assetWriterAppendSampleBufferFailWith:bufferType];
return;
}
if (bufferType == RPSampleBufferTypeVideo) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.videoAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.videoAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
if (bufferType == RPSampleBufferTypeAudioMic) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.audioAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.audioAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
} completionHandler:^(NSError * _Nullable error) {
//deal with error
}];
}
and than ,when want to save it :
-(void)stopRecording {
if([[RPScreenRecorder sharedRecorder] isRecording]){
// The problem is sporadic,recording action failed,it makes me confused
}
[[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {
if(!error) {
//post message
}
}];
}
I've been trying to add a header to the tabSection of the tabview in tvos 18+ .
init(
@TabContentBuilder<SelectionValue> content: () -> Content,
@ViewBuilder header: () -> Header
) where Header : View, Footer == EmptyView
Here the ehader clearly conforms to View but i cant quite fit the label with uiimage as the icon into this. This Label when i add it to any other view, the image is in the specified 50 x 50 size but inside header it functions weirdly to be of a huge size. but also to note, if i simply hav an icon here, it is correct. So what is the problem here.. can someone help me? im supposed to add the user profile and name in the header. I dont think there's any other way
I want to add the option to choose an alternative icon inside the app.
Is there a way to load an icon asset from within the app? I downloaded Apple’s alternative icon sample, which is supposed to show a list of icons to choose from, but even in the sample, it did not work.
So the current solution is to add every alternative icon along with another image asset of the same image to display to the user. This sounds like a waste of bytes.
Thank you in advance for any help.
Topic:
UI Frameworks
SubTopic:
General
private let datePicker = {
let picker = UIDatePicker()
picker.backgroundColor = .clear
picker.datePickerMode = .dateAndTime
picker.preferredDatePickerStyle = .compact
return picker
}()
I set UIToolbar and UIBarButtonItem to UITextField placed on Xib, but when I run it on iOS18 iPad, the following error is output to Xcode Console, and UIPickerView set to UITextField.inputView is not displayed.
Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem.
If you want to see the backtrace, please set CG_NUMERICS_SHOW_BACKTRACE environmental variable.
Backtrace:
<CGPathAddLineToPoint+71>
<+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadii:segments:smoothPillShapes:clampCornerRadii:]
<+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadius:segments:]+175>
<+[UIBezierPath _roundedRectBezierPath:withRoundedCorners:cornerRadius:segments:legacyCorners:]+338>
<-[_UITextMagnifiedLoupeView layoutSubviews]+2233>
<__56-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]_block_invoke+89>
<+[UIView(UIViewAnimationWithBlocksPrivate) _modifyAnimationsWithPreferredFrameRateRange:updateReason:animations:]+166>
<block_destroy_helper.269+92>
<block_destroy_helper.269+92>
<__swift_instantiateConcreteTypeFromMangledName+94289>
<block_destroy_helper.269+126>
<+[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:anima
<block_destroy_helper.269+6763>
<block_destroy_helper.269+10907>
<-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]+389>
<-[_UITextMagnifiedLoupeView setVisible:animated:completion:]+256>
<-[UITextLoupeSession _invalidateAnimated:]+329>
<-[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity:
<-[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCanc
<-[UITextRefinementInteraction loupeGesture:]+701>
<-[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]+71>
<_UIGestureRecognizerSendTargetActions+100>
<_UIGestureRecognizerSendActions+306>
<-[UIGestureRecognizer _updateGestureForActiveEvents]+704>
<_UIGestureEnvironmentUpdate+3892>
<-[UIGestureEnvironment _updateForEvent:window:]+847>
<-[UIWindow sendEvent:]+4937>
<-[UIApplication sendEvent:]+525>
<__dispatchPreprocessedEventFromEventQueue+1436>
<__processEventQueue+8610>
<updateCycleEntry+151>
<_UIUpdateSequenceRun+55>
<schedulerStepScheduledMainSection+165>
<runloopSourceCallback+68>
<__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+17>
<__CFRunLoopDoSource0+157>
<__CFRunLoopDoSources0+293>
<__CFRunLoopRun+960>
<CFRunLoopRunSpecific+550>
<GSEventRunModal+137>
<-[UIApplication _run]+875>
<UIApplicationMain+123>
<__debug_main_executable_dylib_entry_point+63>
10d702478 204e57345
Type: Error | Timestamp: 2025-03-09 00:22:46.121407+09:00 | Process: FurusatoLocalCurrency | Library: CoreGraphics | Subsystem: com.apple.coregraphics | Category: Unknown process name | TID: 0x5c360
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)
(
"<NSAutoresizingMaskLayoutConstraint:0x600002202a30 h=--& v=--& _UIToolbarContentView:0x7fc2c6a5b8f0.width == 0 (active)>",
"<NSLayoutConstraint:0x600002175e00 H:|-(0)-[_UIButtonBarStackView:0x7fc2c6817b10] (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>",
"<NSLayoutConstraint:0x600002175e50 H:[_UIButtonBarStackView:0x7fc2c6817b10]-(0)-| (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>",
"<NSLayoutConstraint:0x6000022019f0 'TB_Leading_Leading' H:|-(8)-[_UIModernBarButton:0x7fc2a5aa8920] (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>",
"<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>",
"<NSLayoutConstraint:0x600002201e50 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.leading == _UIButtonBarButton:0x7fc2f57117f0.leading (active)>",
"<NSLayoutConstraint:0x600002201ea0 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.trailing == UIView:0x7fc2a5aac8e0.trailing (active)>",
"<NSLayoutConstraint:0x6000022021c0 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2f57117f0]-(0)-[UIView:0x7fc2a5aa8330] (active)>",
"<NSLayoutConstraint:0x600002202210 'UISV-spacing' H:[UIView:0x7fc2a5aa8330]-(0)-[_UIButtonBarButton:0x7fc2a5aa84d0] (active)>",
"<NSLayoutConstraint:0x600002202260 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2a5aa84d0]-(0)-[UIView:0x7fc2a5aac8e0] (active)>",
"<NSLayoutConstraint:0x600002176f30 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>",
"<NSLayoutConstraint:0x600002176e40 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide']-(0)-|(LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Hi,
Is there any way of changing the contentInset (UIKit variant) of a List in SwiftUI?
I do not see any APIs for doing so, the closest I gotten is to use safeAreaInset . While visually that works the UX is broken as you can no longer "scroll" from the gap made by the .safeAreaInset(edge:alignment:spacing:content:)
I have subbmited a feedback suggestion: FB16866956
Hi,
I’m practicing with NavigationSplitView for macOS and customizing the sidebar. I’ve managed to adjust most parts, but I couldn’t remove the sidebar’s divider. It seems like it’s not possible in modern SwiftUI. My AppKit knowledge is also not very strong.
How can I remove the sidebar divider?
I want to use a plain background. I also solved it by creating my own sidebar, but I wanted to try it using NavigationSplitView.