Hi,
I am in need of a solution that takes data from SwiftData classes and generates a PDF with the given data. Any guidance would be greatly appreciated.
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
Starting with iOS 18, the behavior of searchable and searchSuggestions differs from previous versions.
In iOS 17.5, searchSuggestions remained visible even after selecting an item and navigating away. However, in iOS 18, searchSuggestions are dismissed after navigation.
Is there a way to keep searchSuggestions visible after navigation, as in iOS 17.5?
struct ContentView: View {
@State private var query = ""
var body: some View {
NavigationStack {
Color.red
.searchable(text: $query)
.searchSuggestions {
NavigationLink("Element") {
Color.blue
}
}
}
}
}
iOS 18.1
iOS 17.5
I have a grid-like container with subviews.
I recently changed some internal details of the subviews, so that changes to the values they display animate.
Now, the behaviour of the grid container has changed: the animation duration used for the internal changes is now also used when the grid is re-ordered or subviews are added or removed.
I can see why this happens: the grid repositions the subviews, and the subview has declared an animation that applies to all of its properties however they are modified.
This doesn't seem like a good idea to me. The principle of encapsulation suggests that I should be able to make internal changes to a component without suffering "spooky action at a distance", i.e. other components unexpectedly changing their behaviour.
Is this an inherent issue with SwiftUI animations, or does it suggest that I am doing something wrong?
After uploading the app to App Store Connect, Apple automatically generated a Default App Clip Link. However, the App Clip card only opens successfully if the main app is already installed on the device. If the main app is not installed, the App Clip card displays an image and the message "App Clip Unavailable"
What could cause this behavior, and how do I ensure the App Clip works without requiring the main app to be installed?
private let datePicker = {
let picker = UIDatePicker()
picker.backgroundColor = .clear
picker.datePickerMode = .dateAndTime
picker.preferredDatePickerStyle = .compact
return picker
}()
Its important to note that this same app did not have this issue in iOS 17.
Ever since iOS 18 I have noticed that when application written in SwiftUI uses Label with the default color (which auto changes between light and dark appearance), from time to time when resuming an application that has been in the background, the color of those labels (only the Label elements) switches from the opposite to the correct one. Here is an example:
Steps to reproduce
Phone is in dark appearance
Open app
Labels text color is white and labels background is black
Go to home so that app is on background
Wait random time (does not happen all the time), some times 1 min some times 10
Reopen the application.
During the opening transition the Label text color was changed while the app was in suspended mode to the light appearance variant (black)
Once the app opening transition finishes the Label text color switches back to the correct color for dark appearance (white)
Same issue happens if you start from light appearance. I cannot reproduce this on Xcode simulators, I have tried to force memory warning to check if that has anything to do with it but that also does not cause the issue to appear on simulators. For now I can only reproduce this on real device.
Screenshots
Here is screenshots of the above example:
During transition
After transition
Topic:
UI Frameworks
SubTopic:
SwiftUI
If two NavigationStacks are nested with the inner stack in a sheet NavigationLinks in the inner stack open as expected in the inner stack.
struct ContentView: View {
var body: some View {
NavigationStack {
Color.clear
.sheet(isPresented: .constant(true)) {
NavigationStack {
ExampleList()
.navigationTitle("Inner Navigation Stack")
}
.presentationDetents([.medium])
}
.navigationTitle("Outer Navigation Stack")
}
}
}
If I try the same with an overlay instead of a sheet, NavigationLinks in the inner stack unexpectedly open in the outer stack.
struct ContentView: View {
var body: some View {
NavigationStack {
Color.clear
.overlay(alignment: .bottomTrailing) {
NavigationStack {
ExampleList()
.navigationTitle("Inner Navigation Stack")
}
.frame(width: 200, height: 250)
.border(.black, width: 5)
.padding()
.presentationDetents([.medium])
}
.navigationTitle("Outer Navigation Stack")
}
}
}
Even the navigation title for the outer stack is being overridden by the inner stack's navigation title.
TLDR
What magic is sheet using that allows for nested NavigationStacks and how might I approach getting this to work in an overlay?
iOS 18.2
Xcode 16.2
The definition of ExampleList for reproducibility:
struct ExampleList: View {
var body: some View {
List(1..<5) { number in
NavigationLink("\(number)") {
Text("\(number)")
.font(.largeTitle)
}
}
}
}
When integrating SwiftData for an already existing app that uses CoreData as data management, I encounter errors.
When building the ModelContainer for the first time, the following error appears:
Error: Persistent History (184) has to be truncated due to the following entities being removed (all Entities except for the 2 where I defined a SwiftData Model)
class SwiftDataManager: ObservableObject {
static let shared = SwiftDataManager()
private let persistenceManager = PersistenceManager.shared
private init(){}
lazy var modelContainer: ModelContainer = {
do {
let storeUrl = persistenceManager.storeURL()
let schema = Schema([
HistoryIncident.self,
HistoryEvent.self
])
let modelConfig = ModelConfiguration(url: storeUrl)
return try ModelContainer(for: schema, configurations: [modelConfig])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
}
@Model public class HistoryIncident {
var missionNr: String?
@Relationship(deleteRule: .cascade) var events: [HistoryEvent]?
public init(){}
}
@Model class HistoryEvent {
var decs: String?
var timestamp: Date?
init(){}
}
As soon as I call the following function.
func addMockEventsToCurrentHistorie() {
var descriptor = FetchDescriptor<HistoryIncident>()
let key = self.hKey ?? ""
descriptor.predicate = #Predicate { mE in
key == mE.key
}
let historyIncident = try? SwiftDataManager.shared.modelContext.fetch(descriptor).first
guard var events = historyIncident?.events else {return}
events.append(contentsOf: createEvents())
}
I get the error:
CoreData: error: (1) I/O error for database at /var/mobile/Containers/Data/Application/55E9D59D-48C4-4D86-8D9F-8F9CA019042D/Library/ Private Documents/appDatabase.sqlite. SQLite error code:1, 'no such column: t0.Z1EVENTS'
/var/mobile/Containers/Data/Application/55E9D59D-48C4-4D86-8D9F-8F9CA019042D/Library/ Private Documents/appDatabase.sqlite. SQLite error code:1, 'no such column: t0.Z1EVENTS' with userInfo of { NSFilePath = "/var/mobile/Containers/Data/Application/55E9D59D-48C4-4D86-8D9F-8F9CA019042D/Library/ Private Documents/appDatabase.sqlite"; NSSQLiteErrorDomain = 1; }
Using gesture recognizers it is easy to implement a long-press gesture to open a menu, show a preview or something else on the iOS platform. And you can provide the duration the user must hold down the finger until the gesture recognizer fires.
But I could not yet find out how to determine the default duration for a long-press gesture that is configured in the system settings within the "accessibility" settings under "Haptic Touch" (the available options are fast, standard and slow here).
Is it possible to read out this setting, so my App can adapt to this system setting as well?
In iOS 18, using TextKit to calculate the height of attributed strings is inaccurate. The same method produces correct results in systems below iOS 18.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 40, 100, 0)];
textView.editable = NO;
textView.scrollEnabled = NO;
textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
textView.textContainer.lineFragmentPadding = 0;
textView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:textView];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"陈家坝好吃的撒海程邦达不差大撒把传达是吧才打卡吃吧金卡多措并举哈不好吃大杯茶十八次是吧"];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 4;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attributedString.length)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, attributedString.length)];
textView.attributedText = attributedString;
CGFloat height = [self test:attributedString];
textView.frame = CGRectMake(20, 40, 100, height);
}
- (CGFloat)test:(NSAttributedString *)attString {
// 创建 NSTextStorage 并设定文本内容
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attString];
// 创建 NSLayoutManager 并关联 NSTextStorage
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
// 创建 NSTextContainer 并设定其属性
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(100, CGFLOAT_MAX)];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
// 强制布局管理器计算布局
[layoutManager ensureLayoutForTextContainer:textContainer];
// 获取文本内容所占的高度
CGFloat height = [layoutManager usedRectForTextContainer:textContainer].size.height;
// 返回四舍五入高度
return ceil(height);
}
With iPadOS 18, the UITabBar now defaults to the floating style. I successfully reverted the tab bar to its traditional style by overriding the UITabBarController's horizontalSizeClass property:
self.tabBarController?.traitOverrides.horizontalSizeClass = .unspecified
When I launch the app on my Mac using Apple Silicon, TWO tab bars appear:
One appears at the bottom of the screen, like a traditional tab bar.
The second tab bar is still embedded in the app toolbar in its floating style.
Is this a bug? How do you ensure that overriding the horizontalSizeClass will remove/hide the floating tab bar when running an app on Apple Silicon? TIA!
(Demonstrated on a test project)
I’m encountering an issue with SwiftUI navigation in iOS 18, where navigating to a DetailView causes unexpected duplication of navigation behavior when @Environment(.dismiss) is used.
Code Example: Here’s a simplified version of the code:
struct ContentView: View {
var body: some View {
NavigationStack {
NavigationLink("Go to Detail View", destination: DetailView())
.padding()
}
}
}
struct DetailView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
let _ = print("DetailView") // This print statement is triggered twice in iOS 18
}
}
}
Issue:
In iOS 18, when @Environment(.dismiss) is used in DetailView, the print("DetailView") statement is triggered twice.
The same code works correctly in iOS 17 and earlier, where the print statement is only triggered once, as expected.
However, when I remove @Environment(.dismiss) from DetailView, the code works as intended in iOS 18, with the print statement being triggered only once and no duplication of navigation behavior.
Alternative Approach with .navigationDestination(for:): I also tested using .navigationDestination(for:) to handle navigation:
struct ContentView: View {
var body: some View {
NavigationStack {
NavigationLink("Go to Detail View", destination: DetailView())
.padding()
}
}
}
struct DetailView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
let _ = print("DetailView") // This print statement is triggered twice in iOS 18
}
}
}
Even with this alternative approach, the issue persists in iOS 18, where the print statement is triggered twice.
What I've Tried:
I’ve confirmed that removing @Environment(.dismiss) solves the issue, and the print statement is triggered only once, and the navigation works as expected in iOS 18 without duplication.
The issue only occurs when @Environment(.dismiss) is in use, which seems to be tied to the navigation stack behavior. The code works correctly in iOS 17 and below, where the print statement is only called once.
Expected Behavior:
I expect the print("DetailView") statement to be called once when navigating to DetailView, and that the navigation happens only once without duplication. The presence of @Environment(.dismiss) should not cause the navigation to be triggered multiple times.
Questions:
Is this a known issue with iOS 18 and SwiftUI navigation? Specifically, is there a new behavior that interacts differently with @Environment(.dismiss)?
Has anyone else encountered this problem, and if so, what’s the recommended way to handle it in iOS 18?
Is there a workaround to ensure that the navigation doesn’t trigger more than once when using @Environment(.dismiss) in iOS 18?
Any help or insights would be greatly appreciated!
How do I draw a single line of text in a SwiftUI Canvas, scaled to fill a given rectangle?
Example:
Canvas { context, size in
let r = CGRect(origin: CGPointZero, size: size); // Whole canvas
let t = Text("Hello World");
context.draw(t, in: r);
}
Outside of Canvas I'd add .minimumScaleFactor(0) .lineLimit(1), and I guess set a large default font size, and I'd get the result I want.
But inside Canvas, .minimumScaleFactor and .lineLimit don't seem to be available; they return some View, not Text, which can't be used in context.draw. (Is there a trick to make that work?)
I have written the following to do this, but I think there must be an easier way to achieve this! Suggestions?
extension GraphicsContext {
mutating func draw_text_in_rect(string: String, rect: CGRect)
{
let text = Text(string) .font(.system(size: 25));
// The font size used here does matter, because e.g. letter spacing
// varies with the font size.
let resolved = resolve(text);
let text_size = resolved.measure(in: CGSize(width: CGFloat.infinity, height: CGFloat.infinity));
let text_aspect = text_size.width / text_size.height;
let fit_size = CGSize(width: min(rect.size.width, rect.size.height*text_aspect),
height: min(rect.size.height, rect.size.width/text_aspect));
let fit_rect = CGRect(x: rect.origin.x + (rect.size.width-fit_size.width)/2,
y: rect.origin.y + (rect.size.height-fit_size.height)/2,
width: fit_size.width,
height: fit_size.height);
let scale = fit_size.width / text_size.width;
// For debug:
// var p = Path();
// p.addRect(fit_rect);
// stroke(p, with: GraphicsContext.Shading.color(.red), lineWidth: 1);
translateBy(x: fit_rect.minX, y: fit_rect.minY);
scaleBy(x:scale, y:scale);
draw(resolved, at: CGPointZero, anchor: UnitPoint.topLeading);
transform = CGAffineTransformIdentity;
}
};
I have a SwiftUI view of the form
struct ContentView: View {
// ...
.onDrop(of: [.pdf], isTargeted: $isDropTargeted) { pdfs in
for pdf in pdfs {
I'm just not sure what to do next, I see there's a loadPreviewImage() that if I use like:
Task.detached {
// returns any NSSecureCoding object
let image = try! await pdf.loadPreviewImage()
}
Not sure how I'm supposed to get my preview image from that NSSecureCoding object
Topic:
UI Frameworks
SubTopic:
SwiftUI
hi does any one know if there changes in lifecycle in xcode 16 ios 18 cause i notice that my view will appear does what view didappear use to do in older version and it kind of a problem cause all the rest of ios work diffrently does anyone else found a problem with it?
or does anyone know if there was a known change to life cycles
I am creating an application that uses VNDetectBarcodesRequest to read QR codes from images and adjust the image orientation to match that of the QR code finder pattern.
The QR code was successfully read, and the coordinates of the QR code were obtained.Upon checking the obtained topLeft, topRight, and bottomLeft coordinates, they always seem to match the topLeft, topRight, and bottomLeft coordinates of the finder pattern.
Is it specified that the coordinates of topLeft, topRight, and bottomLeft obtained with VNDetectBarcodesRequest match the topLeft, topRight, and bottomLeft of the finder pattern? Or do they just happen to match?
I would appreciate it if you could tell me if the matching of coordinates is a specification.
Thank you for your help.
After the user clicks the Open button in the AppClip card, the AppClip launches, but the card keeps appearing whenever the user clicks Open. It doesn’t disappear until the user clicks the Close button on the card.
This issue started appearing two months ago and only occurs on iOS 17.6 and 17.7.
[demo video](https://drive.google.com/file/d/1vJ-7E5JSdO_xoVkDYxBJDkj8sm-dvxv1/view?usp=share_link
Topic:
UI Frameworks
SubTopic:
General
Hi.
I know to know which window gets hardware keyboard events (such as shortcut key) currently on iPad.
Until iPadOS 15.0, UIApplication.shared.keyWindow, which was deprecated on iPadOS 13.0 and didBecomeKeyNotification/didResignKeyNotification.
But after iPadOS 15.0, a keyWindow is managed by UIScene, not by UIApplication.
Each scene of my app always has just one window.
For my purpose, checking deprecated UIApplication.shared.keyWindow is still effective but didBecomeKeyNotification and didResignKeyNotification don't work because they are fired when a change happens only inside the scene.
So my questions are,
What is the new alternative of UIApplication.shared.keyWindow?
I know a wrong hack like
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first?.windows.filter { $0.isKeyWindow }.first
does not work since the order of connectedScenes is not related with getting hardware keyboard events.
What are the new alternatives of didBecomeKeyNotification/didResignKeyNotification which work on inter-scene?
The second question is more crucial.
Because about the first question, I can still use deprecated UIApplication.shared.keyWindow.
Thanks.
We have developed an iOS app using three fonts: PingFangSC Regular, PingFangSC Medium, and DINAlternate-Bold. Do all three fonts require commercial authorization to be used in the app?
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