Search results for

swiftui

16,580 results found

Post

Replies

Boosts

Views

Activity

Best practice for centralizing SwiftData query logic and actions in an @Observable manager?
I'm building a SwiftUI app with SwiftData and want to centralize both query logic and related actions in a manager class. For example, let's say I have a reading app where I need to track the currently reading book across multiple views. What I want to achieve: @Observable class ReadingManager { let modelContext: ModelContext // Ideally, I'd love to do this: @Query(filter: #Predicate { $0.isCurrentlyReading }) var currentBooks: [Book] // ❌ But @Query doesn't work here var currentBook: Book? { currentBooks.first } func startReading(_ book: Book) { // Stop current book if any if let current = currentBook { current.isCurrentlyReading = false } book.isCurrentlyReading = true try? modelContext.save() } func stopReading() { currentBook?.isCurrentlyReading = false try? modelContext.save() } } // Then use it cleanly in any view: struct BookRow: View { @Environment(ReadingManager.self) var manager let book: Book var body: some View { Text(book.title) Button(Start Reading) { manager.startReading(book) } if man
0
0
110
1w
Reply to SwiftUI @State Updates Not Reflecting in UI Until View Reconstruction (Xcode Preview & Device)
Update: Issue Resolved! 🎉 Thanks again for testing on your setup! Your feedback helped me realize this might be an environment-specific issue. Root Cause Found After extensive debugging, I identified two key problems: Performance bottleneck during initialization: A utility manager was making repeated I/O calls on every UI update, flooding the console with 100+ log statements on first load. SwiftUI subscription mechanism timing: In Xcode Preview (specifically on macOS 26.1 + Xcode 26.2), when the main thread is heavily loaded during ContentView initialization, the @State → View update subscription doesn't properly establish. Solution Part 1: Performance optimization Added caching for expensive operations Removed excessive logging (100+ lines → 3 lines) Pre-loaded resources instead of loading on-demand Part 2: Preview-specific fix struct ContentView: View { @State private var refreshTrigger: Int = 0 var body: some View { // ... content .id(refreshTrigger) // Force rebuild when id changes .onAppear { /
Topic: UI Frameworks SubTopic: SwiftUI
1w
Reply to SwiftUI @State Updates Not Reflecting in UI Until View Reconstruction (Xcode Preview & Device)
Thanks for your reply! Here's the complete code and detailed information: Issue Description I'm experiencing a strange behavior with Xcode Preview in my SwiftUI app: On first Preview load: Button taps don't respond at all Temporary workaround: Click any other file, then click back to ContentView - buttons work perfectly Reproducibility: Happens 100% of the time after cleaning and restarting Preview Environment Xcode Version: Version 26.2 iOS Target: iOS 26.1 macOS Version: 26.1 Reproducibility: 100% consistent Relevant Code App Entry Point import SwiftUI import AVFoundation @main struct MyApp: App { init() { setupAudioSession() } private func setupAudioSession() { do { try AVAudioSession.sharedInstance().setCategory( .playback, mode: .default, options: [.mixWithOthers] ) try AVAudioSession.sharedInstance().setActive(true) } catch { print(Failed to setup audio session: (error)) } } var body: some Scene { WindowGroup { ContentView() } } }### ContentView - Simplified Version import SwiftUI
Topic: UI Frameworks SubTopic: SwiftUI
1w
Reply to findNavigator
I'm coding in swiftUI. I've a TextEditor. When I make appear the findNavigator of this TextEditor I want to copy a string to the searchText by program when it appears. I think it's possible to copy this string to the findNavigator but I don't know how to do this. Perhaps sending a copy command to the view ancestor ?
1w
SwiftUI @State Updates Not Reflecting in UI Until View Reconstruction (Xcode Preview & Device)
Issue Description I'm experiencing a bizarre SwiftUI state update issue that only occurs in Xcode development environment (both Canvas preview and device debugging), but does not occur in production builds downloaded from App Store. Symptom: User taps a button that modifies a @State variable inside a .sheet Console logs confirm the state HAS changed But the UI does not update to reflect the new state Switching to another file in Xcode and back to ContentView instantly fixes the issue The production build (same code) works perfectly fine Environment Xcode: 16F6 (17C52) iOS: 26.2 (testing on iPhone 13) macOS: 25.1.0 (Sequoia) SwiftUI Target: iOS 15.6+ Issue: Present in both Xcode Canvas and on-device debugging Production: Same code works correctly in App Store build (version 1.3.2) Code Structure Parent View (ContentView.swift) struct ContentView: View { @State private var selectedSound: SoundTheme = .none @State private var showSoundSheet = false var body: some View { VStack { // Display butt
Topic: UI Frameworks SubTopic: SwiftUI
6
0
338
1w
Reply to What is the best way to push iOS26 List content up on TextField keyboard focused?
More example here: // // ListSafeAreaBarKeyboardTextField.swift // Exploration import SwiftUI import Foundation struct ListSafeAreaBarKeyboardTextField: View { @State private var typedText: String = @FocusState private var focusingTextField: Bool private let items = Array(1...16) var body: some View { ScrollViewReader { proxy in List { ForEach(items, id: .self) { number in Text(Item (number)) .id(number) } Text(Scroll to This) .id(ScrollToThis) } .defaultScrollAnchor(.bottom) .onAppear { if let lastItem = items.last { proxy.scrollTo(lastItem, anchor: .bottom) } } .onChange(of: focusingTextField) { oldValue, newValue in // if TextField is focused if newValue == true { // We scroll to the known last item (ScrollToThis) // ❌ (Somehow) This simply never works withAnimation { proxy.scrollTo(ScrollToThis, anchor: .bottom) } } } } .scrollDismissesKeyboard(.interactively) .safeAreaBar(edge: .bottom) { TextField(Type here, text: $typedText, axis: .vertical) .focused($focusingTextField) // Design .padding(.ho
Topic: UI Frameworks SubTopic: SwiftUI Tags:
1w
What is the best way to push iOS26 List content up on TextField keyboard focused?
Code example: // // ListSafeAreaBarKeyboardTextField.swift // Exploration import SwiftUI import Foundation struct ListSafeAreaBarKeyboardTextField: View { @State private var typedText: String = @FocusState private var focusingTextField: Bool private let items = Array(1...16) var body: some View { ScrollViewReader { proxy in List(items, id: .self) { number in Text(Item (number)) .id(number) } .onAppear { if let lastItem = items.last { proxy.scrollTo(lastItem, anchor: .bottom) } } .onChange(of: focusingTextField) { oldValue, newValue in // This simply won't work // ~ 12th - 16th item will still get covered by keyboard if newValue == true { // Delay to allow keyboard animation to complete DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { if let lastItem = items.last { withAnimation { proxy.scrollTo(lastItem, anchor: .top) } } } } } } .scrollDismissesKeyboard(.interactively) .safeAreaBar(edge: .bottom) { TextField(Type here, text: $typedText, axis: .vertical) .focused($focusingTextField) // Design
1
0
114
1w
How To Set Custom Icon for Control Center Shortcuts
How do I set a custom icon for an app control that appears in Control Shortcuts (swipe down from iOS) ? Where is the documentation for size and where to put the image, format etc? Thank you. Working Code (sfsymbol) import Foundation import AppIntents import SwiftUI import WidgetKit // MARK: - Open App Control @available(iOS 18.0, *) struct OpenAppControl: ControlWidget { let kind: String = OpenAppControl var body: some ControlWidgetConfiguration { StaticControlConfiguration(kind: kind, content: { ControlWidgetButton(action: OpenAppIntent()) { Label(Open The App, systemImage: clock.fill) } } }) .displayName(Open The App) // This appears in the shortcuts view } } Sample Image These apps use their own image. How can I use my own image?
0
0
32
1w
SwiftData @Model: Optional to-many relationship is never nil at runtime
Hi all, I’m trying to understand SwiftData’s runtime semantics around optional to-many relationships, especially in the context of CloudKit-backed models. I ran into behavior that surprised me, and I’d like to confirm whether this is intended design or a potential issue / undocumented behavior. Minimal example import SwiftUI import SwiftData @Model class Node { var children: [Node]? = nil var parent: Node? = nil init(children: [Node]? = nil, parent: Node? = nil) { self.children = children self.parent = parent print(self.children == nil) } } struct ContentView: View { var body: some View { Button(Create) { _ = Node(children: nil) } } } Observed behavior If @Model is not used, children == nil prints true as expected. If @Model is used, children == nil prints false. Inspecting the macro expansion, it appears SwiftData initializes relationship storage using backing data placeholders and normalizes to-many relationships into empty collections at runtime, even when declared as optional. CloudKit context Fr
0
0
55
1w
Changes in Mouse Event Reporting Frequency in macOS 26.2
I have a Mac application that uses the NSEvent.addLocalMonitorForEvents API to receive all mouse movement events. It receives all the mouse movement events and calculate the event reporting rate. The code used as following: import SwiftUI struct ContentView: View { var body: some View { VStack { Image(systemName: globe) .imageScale(.large) .foregroundColor(.accentColor) Text(Hello, world!) } .frame(width: 400, height: 400) .padding() .onAppear() { // here NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) { event in print(event.timestamp) return event } } } } With the exact same code, before I upgraded my macOS to the latest version 26.2, I could receive approximately 460+ mouse events per second, this matched the hardware reporting frequency of my mouse device perfectly. However, after upgrading to version 26.2, I noticed that the number of mouse events received per second is limited to match the screen refresh rate: when I set the screen refresh rate to 60Hz, I only receive 60 mouse events p
Topic: UI Frameworks SubTopic: AppKit
0
0
113
1w
SwiftUI navigationTransition(.zoom) glitches during interactive swipe-back
Hi everyone 👋 I’m fairly new to iOS development and I’ve been stuck on a SwiftUI issue for a while now, so I’m hoping someone here can spot what I’m doing wrong. I’m using navigationTransition(.zoom) together with matchedTransitionSource to animate navigation between views. The UI consists of a grid of items (currently a LazyVGrid, though the issue seems unrelated to laziness). Tapping an item zooms it into its detail view, which is structurally the same view type and can contain further items. All good expect that interactive swipe-back sometimes causes the item to disappear from the grid once the parent view is revealed. This only happens when dismissing via the drag gesture; it does not occur when using the back button. I’ve attached a short demo showing the issue and the Swift file containing the relevant view code. Is there something obvious I’m doing wrong with navigationTransition / matchedTransitionSource, or is this a known limitation or bug with interactive swipe-back? Thanks in advance. i
Topic: UI Frameworks SubTopic: SwiftUI
2
0
225
1w
Navigation Zoom Transition: Toolbar items and Navigation Title slide horizontally during transition (iOS 18+)
Hello, I am experiencing a layout glitch when using the new .navigationTransition(.zoom) in SwiftUI on iOS 18+. While the primary content transitions smoothly, the Navigation Bar elements (Title and ToolbarItems) of the source view exhibit an unwanted horizontal sliding animation during the transition. The Problem: As the zoom transition begins, the large inline title and the trailing toolbar buttons do not simply fade out or stay pinned. Instead, they slide to the left of the screen and when destination view is closed they slide back to their place. This creates a janky visual effect where the navigation bar appears to collapse or shift its coordinate space while the destination view is expanding. Problem video link:-
0
0
88
1w
On macOS, app's Settings model is not deallocated even after closing Settings window
Problem On the macOS when Settings view is closed, the @State model is not deallocated Feedback FB21393010 Environment macOS: 26.2 (25C56) Xcode: 26.2 (17C52) Steps to reproduce Run the project Open app's 'Settings Look at the console logs When model is created SettingsModel - init gets printed When Settings window is closed SettingsModel - deinit is not printed, meaning it is not deallocated Code SettingsModel import SwiftUI @Observable class SettingsModel { init() { print(SettingsModel - init) } deinit { print(SettingsModel - deinit) } } SettingsView import SwiftUI struct SettingsView: View { @State var model = SettingsModel() var body: some View { Text(Settings) .font(.largeTitle) .padding(200) } } App import SwiftUI @main struct SettingsBugApp: App { var body: some Scene { WindowGroup { ContentView() } Settings { SettingsView() } } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
78
1w
Reply to Instruments: Trace file had no SwiftUI data
Steps: In Xcode, choose Product → Profile Use the standard SwiftUI App template Keep the template settings at their defaults Start a profiling session If I stop the session while the app is still on the home screen, everything usually completes normally Start another profiling session and interact with the app a bit more Observed behavior: Occasionally, after running a longer session, I see a message related to ktrace Even after this appears, I can still sometimes run another short profiling session successfully In other cases, I see a different message indicating that data could not be collected I have also seen a message indicating that no SwiftUI data was available (I don’t currently have a screenshot for this case)
Topic: UI Frameworks SubTopic: SwiftUI Tags:
1w