Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

A Summary of the WWDC25 Group Lab - SwiftUI
At WWDC25 we launched a new type of Lab event for the developer community - Group Labs. A Group Lab is a panel Q&A designed for a large audience of developers. Group Labs are a unique opportunity for the community to submit questions directly to a panel of Apple engineers and designers. Here are the highlights from the WWDC25 Group Lab for SwiftUI. What's your favorite new feature introduced to SwiftUI this year? The new rich text editor, a collaborative effort across multiple Apple teams. The safe area bar, simplifying the management of scroll view insets, safe areas, and overlays. NavigationLink indicator visibility control, a highly requested feature now available and back-deployed. Performance improvements to existing components (lists, scroll views, etc.) that come "for free" without requiring API adoption. Regarding performance profiling, it's recommended to use the new SwiftUI Instruments tool when you have a good understanding of your code and notice a performance drop after a specific change. This helps build a mental map between your code and the profiler's output. The "cause-and-effect graph" in the tool is particularly useful for identifying what's triggering expensive view updates, even if the issue isn't immediately apparent in your own code. My app is primarily UIKit-based, but I'm interested in adopting some newer SwiftUI-only scene types like MenuBarExtra or using SwiftUI-exclusive features. Is there a better way to bridge these worlds now? Yes, "scene bridging" makes it possible to use SwiftUI scenes from UIKit or AppKit lifecycle apps. This allows you to display purely SwiftUI scenes from your existing UIKit/AppKit code. Furthermore, you can use SwiftUI scene-specific modifiers to affect those scenes. Scene bridging is a great way to introduce SwiftUI into your apps. This also allows UIKit apps brought to Vision OS to integrate volumes and immersive spaces. It's also a great way to customize your experience with Assistive Access API. Can you please share any bad practices we should avoid when integrating Liquid Glass in our SwiftUI Apps? Avoid these common mistakes when integrating liquid glass: Overlapping Glass: Don't overlap liquid glass elements, as this can create visual artifacts. Scrolling Content Collisions: Be cautious when using liquid glass within scrolling content to prevent collisions with toolbar and navigation bar glass. Unnecessary Tinting: Resist the urge to tint the glass for branding or other purposes. Liquid glass should primarily be used to draw attention and convey meaning. Improper Grouping: Use the GlassEffectContainer to group related glass elements. This helps the system optimize rendering by limiting the search area for glass interactions. Navigation Bar Tinting: Avoid tinting navigation bars for branding, as this conflicts with the liquid glass effect. Instead, move branding colors into the content of the scroll view. This allows the color to be visible behind the glass at the top of the view, but it moves out of the way as the user scrolls, allowing the controls to revert to their standard monochrome style for better readability. Thanks for improving the performance of SwiftUI List this year. How about LazyVStack in ScrollView? Does it now also reuse the views inside the stack? Are there any best practices for improving the performance when using LazyVStack with large number of items? SwiftUI has improved scroll performance, including idle prefetching. When using LazyVStack with a large number of items, ensure your ForEach returns a static number of views. If you're returning multiple views within the ForEach, wrap them in a VStack to signal to SwiftUI that it's a single row, allowing for optimizations. Reuse is handled as an implementation detail within SwiftUI. Use the performance instrument to identify expensive views and determine how to optimize your app. If you encounter performance issues or hitches in scrolling, use the new SwiftUI Instruments tool to diagnose the problem. Implementing the new iOS 26 tab bar seems to have very low contrast when darker content is underneath, is there anything we should be doing to increase the contrast for tab bars? The new design is still in beta. If you're experiencing low contrast issues, especially with darker content underneath, please file feedback. It's generally not recommended to modify standard system components. As all apps on the platform are adopting liquid glass, feedback is crucial for tuning the experience based on a wider range of apps. Early feedback, especially regarding contrast and accessibility, is valuable for improving the system for all users. If I’m starting a new multi-platform app (iOS/iPadOS/macOS) that will heavily depend on UIKit/AppKit for the core structure and components (split, collection, table, and outline views), should I still use SwiftUI to manage the app lifecycle? Why? Even if your new multi-platform app heavily relies on UIKit/AppKit for core structure and components, it's generally recommended to still use SwiftUI to manage the app lifecycle. This sets you up for easier integration of SwiftUI components in the future and allows you to quickly adopt new SwiftUI features. Interoperability between SwiftUI and UIKit/AppKit is a core principle, with APIs to facilitate going back and forth between the two frameworks. Scene bridging allows you to bring existing SwiftUI scenes into apps that use a UIKit lifecycle, or vice versa. Think of it not as a binary choice, but as a mix of whatever you need. I’d love to know more about the matchedTransitionSource API you’ve added - is it a native way to have elements morph from a VStack to a sheet for example? What is the use case for it? The matchedTransitionSource API helps connect different views during transitions, such as when presenting popovers or other presentations from toolbar items. It's a way to link the user interaction to the presented content. For example, it can be used to visually connect an element in a VStack to a sheet. It can also be used to create a zoom effect where an element appears to enlarge, and these transitions are fully interactive, allowing users to swipe. It creates a nice, polished experience for the user. Support for this API has been added to toolbar items this year, and it was already available for standard views.
Topic: UI Frameworks SubTopic: SwiftUI
1
0
919
Jun ’25
iOS 18.1 crash UIHostingView.layoutSubviews() / swift_unknownObjectWeakAssign / objc_storeWeak
We're seeing sporadic crashes on devices running iOS 18.1 - both beta and release builds (22B83). The stack trace is always identical, a snippet of it below. As you can tell from the trace, it's happening in places we embed SwiftUI into UIKit via UIHostingController. Anyone else seeing this? 4 libobjc.A.dylib 0xbe2c _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30 5 libobjc.A.dylib 0xb040 weak_register_no_lock + 396 6 libobjc.A.dylib 0xac50 objc_storeWeak + 472 7 libswiftCore.dylib 0x43ac34 swift_unknownObjectWeakAssign + 24 8 SwiftUI 0xeb74c8 _UIHostingView.base.getter + 160 9 SwiftUI 0x92124 _UIHostingView.layoutSubviews() + 112 10 SwiftUI 0x47860 @objc _UIHostingView.layoutSubviews() + 36
9
1
1.2k
8h
Should TabView with .page style support keyboard left/right navigation automatically?
I’m trying to understand the expected behavior of TabView when using .tabViewStyle(.page) on iPadOS with a hardware keyboard. When I place a TabView in page mode, swipe gestures correctly move between pages. However, left and right arrow keys do nothing by default, even when the view is made focusable. This feels a bit surprising, since paging with arrow keys seems like a natural keyboard interaction when a keyboard is attached. Right now, to get arrow-key navigation working, I have to manually: Make the view focusable Listen for arrow key presses Update the selection state manually This works, but it feels a little tedious for something that seems like it could be built-in. import SwiftUI struct PageTabsExample: View { @State private var selection = 0 private let pageCount = 3 var body: some View { TabView(selection: $selection) { Color.red.tag(0) Color.blue.tag(1) Color.green.tag(2) } .tabViewStyle(.page) .indexViewStyle(.page) .focusable(true) .onKeyPress(.leftArrow) { guard selection > 0 else { return .ignored } selection -= 1 return .handled } .onKeyPress(.rightArrow) { guard selection < pageCount - 1 else { return .ignored } selection += 1 return .handled } } } My questions: Is this lack of default keyboard paging for page-style TabView intentional on iPadOS with a hardware keyboard? Is there a built-in way to enable arrow-key navigation for page-style TabView, or is manual handling the expected approach? Does my approach above look like the “SwiftUI-correct” way to do this, or is there a better pattern for integrating keyboard navigation with paging? For this kind of behavior, is it generally recommended to use .onKeyPress like I’m doing here, or would .keyboardShortcut be more appropriate (for example, wiring arrow keys to actions instead)? Any guidance or clarification would be greatly appreciated. I just want to make sure I’m not missing a simpler or more idiomatic solution. Thanks!
0
0
77
15h
Menu presentation in UIHostingController issues
Looking to see if anyone has experienced this issue, and is aware of any workarounds. With an app migrating towards SwiftUI Views but still using UIKit for primary navigation, my app makes use of UIHostingController to push SwiftUI Views onto a UINavigationController stack in a lot of areas. With iOS 26, I notice that SwiftUI's Menu view really struggles to present when contained in a UIHostingController. An error is logged to the console on presentation, and depending on the UI, the Menu won't present inside of it's container, or will jump around the screen. The bug, it seems is based in a private class UIReparentingView and I am curious if anyone has found a work around for this issue. The error reported is: Adding '_UIReparentingView' as a subview of UIHostingController.view is not supported and may result in a broken view hierarchy. Add your view above UIHostingController.view in a common superview or insert it into your SwiftUI content in a UIViewRepresentable instead. The simplest way to see this issue is to create a new storyboard based project. From the ViewController present a UIHostingController with a SwiftUI view that has a Menu and then simply tap to open the Menu. Thanks for any input!
7
3
439
21h
In SwiftUI, how to animate from an arbitrary corner radius to the corner radius of the display?
I am trying to implement a common UX/UI pattern: one view with rounded corners transitioning to a view that fills the screen (N.B. having the display's corner radius). I got this to work if both corner radiuses are equal to that of the display (see first GIF). However, I cannot seem to get it to work for arbitrary corner radiuses of the smaller view (i.e., the one that does not fill the screen). I expected the be able to combine ContainerRelativeShape with .containerShape (see code), but this left me with a broken transition animation (see second GIF). import SwiftUI struct ContentView: View { @Namespace private var animation @State private var selectedIndex: Int? var body: some View { ZStack { if let selectedIndex = selectedIndex { ContainerRelativeShape() .fill(Color(uiColor: .systemGray3)) .matchedGeometryEffect(id: "square-\(selectedIndex)", in: animation) .ignoresSafeArea() .onTapGesture { withAnimation() { self.selectedIndex = nil } } .zIndex(1) } ScrollView { VStack(spacing: 16) { ForEach(0..<20, id: \.self) { index in if selectedIndex != index { ContainerRelativeShape() // But what if I want some other corner radius to start with? .fill(Color(uiColor: .systemGray5)) .matchedGeometryEffect(id: "square-\(index)", in: animation) .aspectRatio(1, contentMode: .fit) .padding(.horizontal, 12) .onTapGesture { withAnimation() { selectedIndex = index } } // .containerShape(RoundedRectangle(cornerRadius: 20)) // I can add this to change the corner radius, but this breaks the transition of the corners } else { Color.clear .aspectRatio(1, contentMode: .fit) .padding(.horizontal, 12) } } } .padding(.vertical, 16) } } } } #Preview { ContentView() } What am I missing here? How can I get this to work? And where is the mistake in my reasoning?
1
0
76
1d
Buttons on tvOS with text are blurred
When adding buttons to a sheet, on tvOS the text is blurred in the buttons, making it illegible. Feedback: FB21228496 (used GPT to extract an example from my project for a test project to attach here) // ButtonBlurTestView.swift // Icarus // // Test view to reproduce blurred button issue on tvOS // import SwiftUI struct ButtonBlurTestView: View { @State private var showSheet = false @State private var selectedTags: [Int] = [] @State private var newTagName: String = "" // Hardcoded test data private let testTags = [ TestTag(id: 1, label: "Action"), TestTag(id: 2, label: "Comedy"), TestTag(id: 3, label: "Drama"), TestTag(id: 4, label: "Sci-Fi"), TestTag(id: 5, label: "Thriller") ] var body: some View { NavigationStack { VStack { Text("Button Blur Test") .font(.title) .padding() Button("Show Test Sheet") { showSheet = true } .buttonStyle(.borderedProminent) .padding() Text("Tap the button above to open a sheet with buttons inside a Form.") .font(.caption) .foregroundColor(.secondary) .multilineTextAlignment(.center) .padding() } .navigationTitle("Blur Test") .sheet(isPresented: $showSheet) { TestSheetView( selectedTags: $selectedTags, newTagName: $newTagName, testTags: testTags ) } } } } struct TestSheetView: View { @Environment(\.dismiss) private var dismiss @Binding var selectedTags: [Int] @Binding var newTagName: String let testTags: [TestTag] var body: some View { NavigationStack { VStack { // Header VStack { Text("Testing") .font(.title2) .bold() Text("Test TV Show") .font(.subheadline) .foregroundColor(.secondary) } .padding() // Form with buttons Form { Section(header: Text("Summary")) { Text("This is a test") .font(.subheadline) .foregroundColor(.secondary) } Section(header: Text("Tags")) { tagsSelectionView } } } .navigationTitle("Add") #if !os(tvOS) .navigationBarTitleDisplayMode(.inline) #endif .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Add") { dismiss() } } } } } private var tagsSelectionView: some View { VStack(alignment: .leading) { // Tag pills in a grid let columns = [GridItem(.adaptive(minimum: 80), spacing: 8)] LazyVGrid(columns: columns, alignment: .leading, spacing: 8) { ForEach(testTags, id: \.id) { tag in TagPill( tag: tag, selected: selectedTags.contains(tag.id) ) { if selectedTags.contains(tag.id) { selectedTags.removeAll { $0 == tag.id } } else { selectedTags.append(tag.id) } } } } Divider() // Add new tag button HStack { TextField("New tag name", text: $newTagName) #if os(tvOS) .textFieldStyle(PlainTextFieldStyle()) #else .textFieldStyle(RoundedBorderTextFieldStyle()) #endif Button("Add") { // Test action newTagName = "" } .disabled(newTagName.trimmingCharacters(in: .whitespaces).isEmpty) } } } } // Tag Pill - matches the structure from original project private struct TagPill: View { let tag: TestTag let selected: Bool let action: () -> Void var body: some View { Button(action: action) { Text(tag.label) .font(.callout) .lineLimit(1) .padding(.horizontal, 12) .padding(.vertical, 8) .background( Capsule() .fill(selected ? Color.accentColor : Color.secondary.opacity(0.15)) ) .overlay( Capsule() .stroke(selected ? Color.accentColor : Color.secondary.opacity(0.35), lineWidth: 1) ) .foregroundStyle(selected ? Color.white : Color.primary) .contentShape(Capsule()) } .buttonStyle(.plain) #if os(tvOS) .focusable(true) #endif } } struct TestTag { let id: Int let label: String } #Preview { ButtonBlurTestView() }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
13
1d
Interactive ColumnTable header?
AI's would have me believe that the header of a TableColumn in Table() can be modified to be interactive simply by adding a header: closure with a Button however no provided code actually compiles or reflects any documentation I can find. Is it possible to put something besides a Text object in the header?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
23
2d
Dual .fileImporter modifier only one is called
On macOS I'm seeing that only one .fileImporter modifier is called when two are defined. Anybody seeing the same issue? The scenario I have is two different file sources share the same file extension but they need to be loaded by two slightly different processes. Select the first option. Nothing happens. Select the second option, it works. Seeing this also in another project. Because the isPresented value is a binding, it isn't straightforward to logically OR the boolean @States and conditionally extract within the import closure. @main struct Dual_File_Importer_ExpApp: App { @State private var showFirstDialog = false @State private var showSecondDialog = false var body: some Scene { DocumentGroup(newDocument: Dual_File_Importer_ExpDocument()) { file in ContentView(document: file.$document) .fileImporter(isPresented: $showFirstDialog, allowedContentTypes: [.commaSeparatedText]) { result in print("first") } .fileImporter(isPresented: $showSecondDialog, allowedContentTypes: [.commaSeparatedText]) { result in print("second") } } .commands { CommandGroup(after: .importExport) { Button("Import First") { showFirstDialog.toggle() } Button("Import Second") { showSecondDialog.toggle() } } } } }```
Topic: UI Frameworks SubTopic: SwiftUI
3
0
154
2d
SwiftUI – How to completely remove the horizontal “ghost lines” inside List with Section and custom rows?
Hi everyone, I’m working on a screen that uses a single SwiftUI List composed of: a top block (statistics, month picker, year selector, total, Entrata/Uscita picker). a list of transactions grouped by day, each group inside its own Section. each row is a fully custom card with rounded corners (RoundedCornerShape) I’m correctly removing all separators using: .listRowSeparator(.hidden) .listSectionSeparator(.hidden) .scrollContentBackground(.hidden) .listStyle(.plain) Each row is rendered like this: TransazioneSwipeRowView(...) .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) .listRowBackground(Color.clear) However, I still see thin horizontal lines appearing between: the search bar and the top block the top block and the start of the list between rows inside the grouped section sometimes at the bottom of a Section These lines are NOT: Divider() system separators backgrounds row borders They seem to be “ghost lines” automatically generated by SwiftUI’s List when multiple consecutive rows or sections are present. Goal I want to remove these lines completely while keeping: native SwiftUI List native scroll behavior swipe-to-delete support grouping by Section custom card-like rows with rounded corners transparent backgrounds What I already tried .plain, .grouped, .insetGrouped list styles .listRowSeparator(.hidden) and .listSectionSeparator(.hidden) .scrollContentBackground(.hidden) clearing all backgrounds adjusting/removing all padding and insets Spacer(minLength: 0) experiments rebuilding the layout using ScrollView + LazyVStack (works perfectly — no lines — BUT loses native swipe-to-delete) There are no Divider() calls anywhere, and no background colors producing borders. Question Is this a built-in behavior of SwiftUI’s List in .plain style when using multiple custom rows, or is there an officially supported way to eliminate these lines entirely? Is there a recommended combination of modifiers to achieve: a List with grouped Sections fully custom rows with rounded backgrounds absolutely no horizontal separators, even in the empty spaces between sections? Any guidance, documented workarounds, WWDC references, or official recommendations would be greatly appreciated. Thanks in advance!
3
0
91
4d
[Issue] Animation of Menu on iOS 26.1
Hello everyone! I found a weird behavior with the animation of Menucomponent on iOS 26.1 When the menu disappear the animation is very glitchy You can find here a sample of code to reproduce it @available(iOS 26.0, *) struct MenuSample: View { var body: some View { GlassEffectContainer { HStack { Menu { Button("Action 1") {} Button("Action 2") {} Button("Delete", role: .destructive) {} } label: { Image(systemName: "ellipsis") .padding() } Button {} label: { Image(systemName: "xmark") .padding() } } .glassEffect(.clear.interactive()) } } } @available(iOS 26.0, *) #Preview { MenuSample() .preferredColorScheme(.dark) } I did two videos: iOS 26.0 iOS 26.1 Thanks for your help
0
0
134
4d
How can I show a movable webcam preview above all windows in macOS without activating the app
I'm building a macOS app using SwiftUI, and I want to create a draggable floating webcam preview window Right now, I have something like this: import SwiftUI import AVFoundation struct WebcamPreviewView: View { let captureSession: AVCaptureSession? var body: some View { ZStack { if let session = captureSession { CameraPreviewLayer(session: session) .clipShape(RoundedRectangle(cornerRadius: 50)) .overlay( RoundedRectangle(cornerRadius: 50) .strokeBorder(Color.white.opacity(0.2), lineWidth: 2) ) } else { VStack(spacing: 8) { Image(systemName: "video.slash.fill") .font(.system(size: 40)) .foregroundColor(.white.opacity(0.6)) Text("No Camera") .font(.caption) .foregroundColor(.white.opacity(0.6)) } } } .shadow(color: .black.opacity(0.3), radius: 10, x: 0, y: 5) } } struct CameraPreviewLayer: NSViewRepresentable { let session: AVCaptureSession func makeNSView(context: Context) -> NSView { let view = NSView() view.wantsLayer = true let previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.videoGravity = .resizeAspectFill previewLayer.frame = view.bounds view.layer = previewLayer return view } func updateNSView(_ nsView: NSView, context: Context) { if let previewLayer = nsView.layer as? AVCaptureVideoPreviewLayer { previewLayer.frame = nsView.bounds } } } This is my SwiftUI side code to show the webcam, and I am trying to create it as a floating window which appears on top of all other apps windows etc. however, even when the webcam is clicked, it should not steal the focus from other apps, the other apps should be able to function properly as they already are. import Cocoa import SwiftUI class WebcamPreviewWindow: NSPanel { private static let defaultSize = CGSize(width: 200, height: 200) private var initialClickLocation: NSPoint = .zero init() { let screenFrame = NSScreen.main?.visibleFrame ?? .zero let origin = CGPoint( x: screenFrame.maxX - Self.defaultSize.width - 20, y: screenFrame.minY + 20 ) super.init( contentRect: CGRect(origin: origin, size: Self.defaultSize), styleMask: [.borderless], backing: .buffered, defer: false ) isOpaque = false backgroundColor = .clear hasShadow = false level = .screenSaver collectionBehavior = [ .canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle ] ignoresMouseEvents = false acceptsMouseMovedEvents = true hidesOnDeactivate = false becomesKeyOnlyIfNeeded = false } // MARK: - Focus Prevention override var canBecomeKey: Bool { false } override var canBecomeMain: Bool { false } override var acceptsFirstResponder: Bool { false } override func makeKey() { } override func mouseDown(with event: NSEvent) { initialClickLocation = event.locationInWindow } override func mouseDragged(with event: NSEvent) { let current = event.locationInWindow let dx = current.x - initialClickLocation.x let dy = current.y - initialClickLocation.y let newOrigin = CGPoint( x: frame.origin.x + dx, y: frame.origin.y + dy ) setFrameOrigin(newOrigin) } func show<Content: View>(with view: Content) { let host = NSHostingView(rootView: view) host.autoresizingMask = [.width, .height] host.frame = contentLayoutRect contentView = host orderFrontRegardless() } func hide() { orderOut(nil) contentView = nil } } This is my Appkit Side code make a floating window, however, when the webcam preview is clicked, it makes it as the focus app and I have to click anywhere else to loose the focus to be able to use the rest of the windows.
0
0
300
4d
SwiftData iCloud AttributedString Platform Color compatibility
Hi Given a simple multiplatform app about Mushrooms, stored in SwiftData, hosted in iCloud using a TextEditor @Model final class Champignon: Codable { var nom: String = "" ../.. @Attribute(.externalStorage) var attributedStringData: Data = Data() var attributedString: AttributedString { get { do { return try JSONDecoder().decode(AttributedString.self, from: attributedStringData) } catch { return AttributedString("Failed to decode AttributedString: \(error)") } } set { do { self.attributedStringData = try JSONEncoder().encode(newValue) } catch { print("Failed to encode AttributedString: \(error)") } } } ../.. Computed attributedString is used in a TextEditor private var textEditorView: some View { Section { TextEditor(text: $model.attributedString) } header: { HStack { Text("TextEditor".localizedUppercase) .foregroundStyle(.secondary) Spacer() } } } Plain Text encode, decode and sync like a charm through iOS and macOS Use of "FontAttributes" (Bold, Italic, …) works the same But use of "ForegroundColorAttributes" trigger an error : Failed to decode AttributedString: dataCorrupted(Swift.DecodingError.Context(codingPath: [_CodingKey(stringValue: "Index 3", intValue: 3), AttributeKey(stringValue: "SwiftUI.ForegroundColor", intValue: nil), CodableBoxCodingKeys(stringValue: "value", intValue: 1)], debugDescription: "Platform color is not available on this platform", underlyingError: nil)) Is there a way to encode/decode attributedString data platform conditionally ? Or another approach ? Thanks for advices
0
0
151
5d
What's the best way to support Genmoji with SwiftUI?
I want to support Genmoji input in my SwiftUI TextField or TextEditor, but looking around, it seems there's no SwiftUI only way to do it? If none, it's kind of disappointing that they're saying SwiftUI is the path forward, but not updating it with support for new technologies. Going back, does this mean we can only support Genmoji through UITextField and UIViewRepresentable? or there more direct options? Btw, I'm also using SwiftData for storage.
1
1
699
5d
SwiftUI List insertion changes aren't animated on macOS 15
I've been struggling with this issue since the release of macOS 15 Sequoia. I'm wondering if anyone else has encountered it or if anyone has a workaround to fix it. Inserting a new element into the array that acts as data source for a SwiftUI List with a ForEach is never animated even if the insertion is wrapped in a withAnimation() call. It seems that some other changes can be automated though: e.g. calls to shuffle() on the array successfully animate the changes. This used to work fine on macOS 14, but stopped working on macOS 15. I created a very simple project to reproduce the issue: import SwiftUI @main struct TestApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct IdentifiableItem: Identifiable { let id = UUID() var name: String { "Item \(id)" } } struct ContentView: View { @State var items: [IdentifiableItem] = [ IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), IdentifiableItem(), ] var body: some View { List { ForEach(items) { item in Text(item.name) } } Button("Add Item") { withAnimation { items.insert(IdentifiableItem(), at: 0) } } Button("Shuffle Items") { withAnimation { items.shuffle() } } } } How to reproduce Copy the code below in an Xcode project. Run it on macOS 15. Hit the "Add Item" button Expected: A new item is inserted with animation. Result: A new item is inserted without animation. How to prove this is a regression Follow the same steps above but run on macOS 14. A new item is inserted with animation.
3
1
597
6d
WebPage and WebView and status bar
I am using WebView and WebPage to display web pages. Some web pages have content fixed to the top of the screen (like apple.com). When this happens, content is under the status bar (like menu buttons), and I cannot tap them. My work around is to put the WebView in a VStack with the top being Color.clear.frame(height: 44). It isn't very elegant, especially since it is applied to all pages and not just pages with fixed content at the top. Is there a more Apple-y way to solve this? For example, Safari seems to detect these situations and puts something like Color.clear.frame(height: 44) in those cases but not other cases. Here is sample code: import SwiftUI import WebKit struct ContentView: View { @State private var page: WebPage init() { let configuration = WebPage.Configuration() page = WebPage(configuration: configuration) let url = URL(string: "https://www.apple.com")! let request = URLRequest(url: url) page.load(request) } var body: some View { WebView(page) } } Here is a screenshot of Apple's page in WebView with the menu Here is a screenshot of Apple's page in Safari. It appears to have inserted a spacer frame at the top for Apple's page (but not, for example, my own web site which doesn't have this problem).
0
0
97
6d
Swift UI Custom Keyboard
How can I correctly display the cursor using a custom keyboard in SwiftUI without using UIKit? Currently, I'm encountering a conflict between the custom keyboard and the system keyboard in SwiftUI, resulting in both keyboards being displayed simultaneously. If I disable the system keyboard and then handle the custom keyboard, the cursor disappears. How can I resolve this issue?it?
0
0
68
1w
Scrolling through long lists with ScrollView and LazyVstack
What is the correct way to implement scrolling in a looong list that uses ScrollView and LazyVstack Imagine I have some api that returns a longs list of comments with replies The basic usecase is to scroll to the bottom(to the last comment) Most of the time this works fine But, imagine some of the comments have many replies like 35 or more (or even 300) User expands replies for the first post, then presses scroll to bottom. The scrollbar reaches the bottom and I see the blank screen. Sometimes the scrollbar may jump for a while before lazyvstack finishes loading or until I manually scroll up a bit or all the way up and down What should I do in this case? Is this the swiftui performance problem that has no cure? Abstract example: ScrollViewReader { proxy in ScrollView { LazyVStack { ForEach(comments) { comment in CommentView(comment: comment) .id("comment-\(comment.id)") } } } } struct CommentView: View { let comment: Comment @State var isExpanded = false var body: some View { VStack { Text(comment.text) if isExpanded { RepliesView(replies: comment.replies) // 35-300+ replies } } } } ... scroll proxy.scrollTo("comment-\(lastComment.id)", anchor: .bottom)
5
0
261
1w
SwiftUI: Menu icon will missing if increase preferred text size
iOS simulator version 18.0+ I have a demo like this: Menu { Button { } label: { Text("Option 1") Image(systemName: "star") } Button { } label: { Text("Option 2") Image(systemName: "star") } } label: { Text("Menu") } And I used the tool Accessibility Inspector to modify the text size. Case 1: We could see the option title and the star icon. Case 2: But we could not see the icon, only the option title here Is this by design from Apple? Or does this need to be fixed? Does anyone know about my question?
0
0
45
1w
WidgetKit with Data from CoreData
I have a SwiftUI app. It fetches records through CoreData. And I want to show some records on a widget. I understand that I need to use AppGroup to share data between an app and its associated widget. import Foundation import CoreData import CloudKit class DataManager { static let instance = DataManager() let container: NSPersistentContainer let context: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "DataMama") container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group identifier)!.appendingPathComponent("Trash.sqlite"))] container.loadPersistentStores(completionHandler: { (description, error) in if let error = error as NSError? { print("Unresolved error \(error), \(error.userInfo)") } }) context = container.viewContext context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } func save() { do { try container.viewContext.save() print("Saved successfully") } catch { print("Error in saving data: \(error.localizedDescription)") } } } // ViewModel // import Foundation import CoreData import WidgetKit class ViewModel: ObservableObject { let manager = DataManager() @Published var records: [Little] = [] init() { fetchRecords() } func fetchRecords() { let request = NSFetchRequest<Little>(entityName: "Little") do { records = try manager.context.fetch(request) records.sort { lhs, rhs in lhs.trashDate! < rhs.trashDate! } } catch { print("Fetch error for DataManager: \(error.localizedDescription)") } WidgetCenter.shared.reloadAllTimelines() } } So I have a view model that fetches data for the app as shown above. Now, my question is how should my widget get data from CoreData? Should the widget get data from CoreData through DataManager? I have read some questions here and also read some articles around the world. This article ( https://dev.classmethod.jp/articles/widget-coredate-introduction/ ) suggests that you let the Widget struct access CoreData through DataManager. If that's a correct fashion, how should the getTimeline function in the TimelineProvider struct get data? This question also suggests the same. Thank you for your reading my question.
7
0
239
1w