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

OS27 LazyVGrid hops like crazy on scroll up.
I’m not sure if this is a ”care later in the summer” situation, but on beta 1, with an .adaptive Grid Item, a scrolling LazyVGrid will hop and “bounce” when scrolling back up from the bottom of the grid. I can see the scrollbar visibly hopping as item views are re-created. Anyone else seeing this?
1
1
37
14h
Menu in the bottom bar flies to the top of the screen
I have a Menu in a Toolbar (specifically, the .bottomBar). If I open the menu quickly after it appears (within a few seconds), it flies to the top of the screen. I've created a minimum woking example below. This appears to be a pretty glaring iOS 26 bug that has been present since the early betas, but I can't seem to find much discussion about it (apart from this post from 8 months ago), so I'm wondering if I might be doing something wrong. Or maybe someone managed to figure out a workaround. If the Menu is very simple (just Text items), it seems to be okay. But if the Menu is even slightly complex (e.g. includes icons), then it exhibits the flying behavior. I've also been able to reproduce this bug under different types of navigation component (e.g. NavigationSplitView). I'm seeing this behavior in the current version of iOS (26.2.1), both on device and in the simulator. MWE struct ContentView: View { var body: some View { NavigationStack { VStack { NavigationLink("Go to Detail") { DetailView() } } .navigationTitle("Root") } } } struct DetailView: View { var body: some View { VStack { Text("Detail View") } .navigationTitle("Detail") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .bottomBar) { Menu { Button { } label: { Label("Delete", systemImage: "trash") } } label: { Image(systemName: "ellipsis.circle") } } } } }
Topic: UI Frameworks SubTopic: SwiftUI
3
1
239
17h
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
2
1
222
17h
MapKit MapCamera
SwiftUI Map with MapCamera jerks on every GPS update instead of animating smoothly I'm trying to make camera to follow the user smoothly during navigation using MapCamera with heading and pitch, similar to Apple Maps or Google Maps. The camera updates on every GPS tick but instead of animating smoothly between positions it jerks , it snaps to the new position, pauses, snaps again, pauses...terrible UX. The blue user location (UserAnnotation) puck moves completely smoothly. Only the camera jerks I have tried all sort of animations and interpolation you may think of. Something is just not right, must be something missing from the puzzle. I have prepared a minimal reproducible example so you can copy and paste the only thing needed is to add the Privacy - Location When In Use Usage Description Run in Simulator, go to Features > Location > Freeway Drive and tap on Track then you'll notice how camera is following then stop then following and stops again Don't bother using AI, he has no clue what's this all about. I also went through docs to find anything useful like a magic modifier, but no joy Here is a video hosted online as well: [https://streamable.com/ear9cv] And a code snippet copy paste import MapKit import CoreLocation // You'll only need to add Privacy - Location When In Use Usage Description to the Info tab struct ContentView: View { @State private var locationManager = LocationManagerDelegate() @State private var cameraPosition: MapCameraPosition = .userLocation(followsHeading: false, fallback: .automatic) @State private var isTracking: Bool = false @State private var lastKnownHeading: Double = 0 var body: some View { Map(position: $cameraPosition) { UserAnnotation() } .onChange(of: locationManager.location) { _, location in guard isTracking, let location else { return } withAnimation(.linear(duration: 0.5)) { cameraPosition = .camera(MapCamera( centerCoordinate: location.coordinate, distance: 1000, heading: location.course, pitch: 60 )) } } .safeAreaInset(edge: .bottom) { // Added to the safeAreaInset to keep the Apple Logo visible Button("Track") { isTracking.toggle() locationManager.requestPermission() locationManager.startNavigating() } .buttonStyle(.glassProminent) .buttonSizing(.flexible) .controlSize(.extraLarge) .padding(.horizontal) } } } @MainActor @Observable final class LocationManagerDelegate: NSObject, CLLocationManagerDelegate { var location: CLLocation? var authorizationStatus: CLAuthorizationStatus = .notDetermined let manager = CLLocationManager() private var liveUpdateTask: Task<Void, Never>? override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation authorizationStatus = manager.authorizationStatus } func requestPermission() { manager.requestWhenInUseAuthorization() } func startNavigating() { liveUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.automotiveNavigation) { guard let newLocation = update.location else { continue } self.location = newLocation } } catch { print("Live updates error: \(error)") } } } func stopNavigating() { liveUpdateTask?.cancel() liveUpdateTask = nil manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus } }
0
0
17
18h
How to build a picker wheel similar as the Calendar App?
How to build the below UI using SwiftUI? I tried to use Picker with wheel style, but it is not the same as the screenshot. The screenshot came from the iOS built-in calendar app. Add a new calendar event Click "Repeat" Choose "Custom" Click "Every day" The required picker wheel will be displayed Picker("Every", selection: $interval) { ForEach(1..<366) { interval in Text("\(interval)").tag(interval) } } .pickerStyle(.wheel)
0
0
22
20h
How do I get SwiftUI to let me determine a custom frame size for NSTextField
I have a NSViewRepresentable that wraps an NSTextField subclass which is displayed as larger than your typical text field. SwiftUI doesn't seem to allow me to set the size of the view when the underlying is an NSTextField. It forces it as a single line field. I've tried both setting the frame on creation as well as using SwiftUI .frame(width:height:) on the represented view. I always end up with a single line field. struct BigTextField: NSViewRepresentable { @Binding var text: String class Coordinator: NSObject, NSTextFieldDelegate { var parent: BigTextField init(_ parent: BigTextField) { self.parent = parent } func controlTextDidChange(_ obj: Notification) { if let textField = obj.object as? NSTextField { parent.text = textField.stringValue } } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSTextField { //let frame = NSRect(x: 0, y: 0, width: 350, height: 140) //let textField = NSTextField(frame: frame) let textField = NSTextField() textField.isEditable = true textField.isBordered = true textField.isBezeled = true textField.delegate = context.coordinator // Assign the coordinator return textField } func updateNSView(_ nsView: NSTextField, context: Context) { if nsView.stringValue != text { nsView.stringValue = text } } } I've also included the SwiftUI declaration which demonstrates the problem. struct ContentView: View { @State var text : String = "Test string" var body: some View { VStack { BigTextField(text: $text) .frame(width: 350, height: 140) } .padding() } } NSTextField can be any arbitrary frame size. I already do this from AppKit but am trying to adapt this custom field to work within SwiftUI. SwiftUI seems to override the sizing of this NSViewRepresentable that I give it. Am I missing something here? Is there some way to override SwiftUI's sizing behavior? Thank you.
0
0
21
1d
Back gesture not disabled with navigationBarBackButtonHidden(true) when using .zoom transition
[Submitted as FB22226720] For a NavigationStack destination, applying .navigationBarBackButtonHidden(true) hides the back button and also disables the interactive left-edge back gesture when using the standard push navigation transition. However, when the destination uses .navigationTransition(.zoom), the back button is hidden but the left-edge back gesture is still available—it can still be dismissed even though back is intentionally suppressed. This creates inconsistent behavior between navigation transition styles. navigationBarBackButtonHidden(_:) works with a standard push transition, but not with .navigationTransition(.zoom). In the code below, .interactiveDismissDisabled(true) is also applied as another attempt to suppress the back-swipe gesture, but it has no effect. As a result, there’s currently no clean way to prevent back navigation when using the zoom transition. REPRO STEPS Create an iOS project then replace ContentView with code below, build and run. Leave nav type set to List Push. Open an item. Verify there is no back button, then try the left-edge back gesture. Return to the root view. Change nav type to Grid Zoom. Open an item. Verify there is no back button, then try the left-edge back gesture. ACTUAL In List Push mode, the left-edge back gesture is prevented. In Grid Zoom mode, the back button is hidden, but the left-edge back gesture still works and returns to the previous view. EXPECTED Behavior should be consistent across navigation transition styles. If this configuration is meant to suppress interactive backward navigation for a destination, it should also suppress the left-edge back gesture when using .navigationTransition(.zoom). SCREEN RECORDING SAMPLE CODE struct ContentView: View { private enum NavigationMode: String, CaseIterable { case listPush = "List Push" case gridZoom = "Grid Zoom" } @Namespace private var namespace @State private var navigationMode: NavigationMode = .listPush private let colors: [Color] = [.red, .blue] var body: some View { NavigationStack { VStack(spacing: 16) { Picker("Navigation Type", selection: $navigationMode) { ForEach(NavigationMode.allCases, id: \.self) { mode in Text(mode.rawValue).tag(mode) } } .pickerStyle(.segmented) if navigationMode == .gridZoom { HStack { ForEach(colors.indices, id: \.self) { index in NavigationLink(value: index) { VStack { RoundedRectangle(cornerRadius: 14) .fill(colors[index]) .frame(height: 120) Text("Grid Item \(index + 1)") .font(.subheadline.weight(.medium)) } .padding(12) .frame(maxWidth: .infinity) .background(.quaternary.opacity(0.25), in: RoundedRectangle(cornerRadius: 16)) .matchedTransitionSource(id: index, in: namespace) } .buttonStyle(.plain) } } } else { ForEach(colors.indices, id: \.self) { index in NavigationLink(value: index) { HStack { Circle() .fill(colors[index]) .frame(width: 24, height: 24) Text("List Item \(index + 1)") Spacer() Image(systemName: "chevron.right") .foregroundStyle(.secondary) } .padding() .background(.quaternary.opacity(0.25), in: RoundedRectangle(cornerRadius: 12)) } .buttonStyle(.plain) } } Spacer() } .padding(20) .navigationTitle("Prevent Back Swipe") .navigationSubtitle("Compare Grid Zoom vs List Push") .navigationDestination(for: Int.self) { index in if navigationMode == .gridZoom { DetailView(color: colors[index]) .navigationTransition(.zoom(sourceID: index, in: namespace)) } else { DetailView(color: colors[index]) } } } } } private struct DetailView: View { @Environment(\.dismiss) private var dismiss let color: Color var body: some View { ZStack { color.ignoresSafeArea() Text("Try left-edge swipe back") .font(.title.bold()) .multilineTextAlignment(.center) .padding(.horizontal, 24) } .navigationBarBackButtonHidden(true) .interactiveDismissDisabled(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", action: dismiss.callAsFunction) } } } }
3
0
712
1d
TextKit 2 + SwiftUI (NSViewRepresentable): NSTextLayoutManager rendering attributes don’t reliably draw/update
I’m embedding an NSTextView (TextKit 2) inside a SwiftUI app using NSViewRepresentable. I’m trying to highlight dynamic subranges (changing as the user types) by providing per-range rendering attributes via NSTextLayoutManager’s rendering-attributes mechanism. The issue: the highlight is unreliable. Often, the highlight doesn’t appear at all even though the delegate/data source is returning attributes for the expected range. Sometimes it appears once, but then it stops updating even when the underlying “highlight range” changes. This feels related to SwiftUI - AppKit layout issue when using NSViewRepresentable (as said in https://developer.apple.com/documentation/swiftui/nsviewrepresentable). What I’ve tried Updating the state that drives the highlight range and invalidating layout fragments / asking for relayout Ensuring all updates happen on the main thread. Calling setNeedsDisplay(_:) on the NSViewRepresentable’s underlying view. Toggling the SwiftUI view identity (e.g. .id(...)) to force reconstruction (works, but too expensive / loses state). Question In a SwiftUI + NSViewRepresentable setup with TextKit 2, what is the correct way to make NSTextLayoutManager re-query and redraw rendering attributes when my highlight ranges change? Is there a recommended invalidation call for TextKit 2 to trigger re-rendering of rendering attributes? Or is this a known limitation when hosting NSTextView inside SwiftUI, where rendering attributes aren’t reliably invalidated? If this approach is fragile, is there a better pattern for dynamic highlights that avoids mutating the attributed string (to prevent layout/scroll jitter)?
4
0
392
2d
Handling View Creation for Heterogeneous Data
In my project (an Package), I have created an Manager (can be classified as an ViewModel) that will handle state updates throughout the Package Component view: Note: The code is simplified for better understanding and to focus on principles behind things I did. The manager does complex things during state updates. public class ComponentManager: ObservedObject { @Published var rows: [any RowProtocol] = [] func updateState(_ newState: any RowProtocolData, id: String) { guard let index = rows.firstIndex(where: { $0.id == id }) else { return } rows[index].updateState(newState) } func getState(id: String) -> any RowProtocolData? { guard let index = rows.firstIndex(where: { $0.id == id }) else { return nil } return rows[index].state } } The RowProtocol is defined as follows: public protocol RowStateProtocol {} public protocol RowProtocol: Identifiable { associatedtype State: RowStateProtocol associatedtype RowView: View var id: String { get } var state: State { get } func updateState(_ newState: State) @MainActor @ViewBuilder func renderRow() -> RowView } extension RowProtocol { func updateState(_ newState: any RowProtocolData) { guard let newState = newState as? State else { return } self.updateState(newState) } } Then in Component View, I need to render the rows based on the underlying type of the row, this where the renderRow() comes in: struct ComponentView: View { @ObservedObject var manager: ComponentManager var body: some View { List { ForEach(manager.rows, id: \.id) { row in HStack { // This HStack prevent List from initing all rows due to AnyView. AnyView(row.renderRow()) } } } } } The row views will be accepting binding to the state of the row and update their state, let says we have a TextRow and a ToggleRow: struct TextRow: RowProtocol { var id: String var state: TextRowState func updateState(_ newState: TextRowState) { self.state = newState } } struct ToggleRow: RowProtocol { var id: String var state: ToggleRowState func updateState(_ newState: ToggleRowState) { self.state = newState } } In this, offcourse we cannot create an binding directly to the state of the row, since the state are through the manager and the row data won't have access to the manager. So I created an property wrapped that use the closures passed by the manager into environment to create the binding and an view that will give the binding to the content view: extenstion EnvironmentValues { @Entry internal var getState: (String) -> any RowStateProtocol? @Entry internal var updateState: (any RowStateProtocol, String) -> Void } @propertyWrapper struct RowStateBinding<State: RowStateProtocol & Equatable>: DynamicProperty { @Environment(\.getState) private var getState @Environment(\.updateState) private var updateState private let id: String init(id: String) { self.id = id } var wrappedValue: State { get { getState(id) as! State } nonmutating set { if wrappedValue != newValue { // only update for an new change, since set can be triggered for any number of reasons. updateState(newValue, id) } } } var projectedValue: Binding<State> { Binding( get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue } ) } } struct RowStateBindingView<Content: View, State: RowStateProtocol & Equatable>: View { @RowStateBinding<State> private var state: State private let content: (Binding<State>) -> Content init(id: String, @ViewBuilder content: @escaping (Binding<State>) -> Content) { self._state = RowStateBinding(id: id) self.content = content } var body: some View { content($state) } } and in the renderRows: struct TextRowView: View { @Binding var text: TextRowState var body: some View { TextField("Enter text", text: $text.text) } } extension TextRow { func renderRow() -> some View { RowStateBindingView(id: id) { state in TextField("Enter text", text: state.text) } } } struct ToggleRowView: View { @Binding var state: ToggleRowState var body: some View { Toggle("Toggle", isOn: $state.isOn) } } extension ToggleRow { func renderRow() -> some View { RowStateBindingView(id: id) { state in Toggle("Toggle", isOn: state.isOn) } } } This way, I can adopt any view as an row view and most importantly, the view can be completely independent of the manager and used as an standalone view. Also clients of the library can create their own custom rows by just conforming to the RowProtocol and creating the view for it, without worrying about how the state management works. The manager will handle all the state updates. I prefer using stucts over classes for rows and states, since its easier to manage state updates. What do you think about this approach? Do you see any potential issues with this? Is there a better way to achieve this?
0
0
20
2d
SwiftUI ​Charts: In iOS 27, annotation overlays exceed the bounds of an annotation
I'm seeing a regression in SwiftUI Charts on iOS 27 beta 1. Any view placed inside a BarMark's overlay annotation no longer receives the size of the parent BarMark. It collapses to zero, so any content sized from geo.size (e.g. a Rectangle meant to fill the bar) renders empty or incorrectly. Expected: The GeometryReader reports the BarMark's rendered width/height, and the Rectangle fills the BarMark (this is the behavior in iOS 26 and earlier). Actual: On iOS 27 beta 1, geo.size is effectively zero, so the overlay content has an extremely small size. I suspect this could be a small bug with the new ContentBuilder / ViewBuilder changes but that's just a hunch. Here's a code sample which reproduces the issue. // MARK: - Mock Data Models struct ScheduleSeries: Identifiable { let id = UUID() let data: [ScheduleItem] } struct ScheduleItem: Identifiable { let id = UUID() let startDate: Date let startHour: Double let endHour: Double let secondaryText: String? } // MARK: - Minimal Reproducible Example struct ContentView: View { // Generate two consecutive days for the mock data let mockSchedule: [ScheduleSeries] = [ ScheduleSeries(data: [ ScheduleItem( startDate: Date(), startHour: 9.0, endHour: 11.5, secondaryText: "Morning Event" ), ScheduleItem( startDate: Calendar.current.date(byAdding: .day, value: 1, to: Date())!, startHour: 13.0, endHour: 16.0, secondaryText: "Afternoon Event" ) ]) ] var body: some View { VStack(alignment: .leading) { Text("FB: Annotation Sizing Bug") .font(.headline) .padding(.bottom, 8) Text("Expected: The gray Rectangle should stretch to fill the BarMark.\nActual: GeometryReader/Annotation fails to size to the parent BarMark.") .font(.caption) .foregroundColor(.secondary) .padding(.bottom) Chart(mockSchedule) { series in ForEach(series.data, id: \.startDate) { element in BarMark( x: .value("Day", element.startDate, unit: .day, calendar: .current), yStart: .value("Start", element.startHour), yEnd: .value("End", element.endHour), width: .ratio(0.99) ) .annotation(position: .overlay, alignment: .topLeading) { item in ZStack { VStack(alignment: .leading, spacing: 0) { // BUG DEMONSTRATION: // This GeometryReader and Rectangle previously filled the BarMark, but in Xcode 27 it does not GeometryReader { geo in Rectangle() .fill(Color.black.opacity(0.15)) .frame(width: geo.size.width, height: geo.size.height) } } .foregroundColor(.white) .font(.caption2) } } } } .chartYScale(domain: 0...24) // Lock the Y-axis to a 24-hour scale } .padding() } } Environment: Xcode 27 beta 1 / iOS 27 beta 1 Reproduces on device and Simulator Worked as expected on iOS 26 and earlier Here's what the issue looks like in our app with zero code changes: iOS 26 iOS 27 I've filed a feedback report (FB23016343) with a sample project attached. Has anyone else hit this, or found a workaround for sizing overlay annotation content to a BarMark in iOS 27? Thanks!
0
0
24
2d
How to detect backspace in SwiftUI TextField without falling back to UIViewRepresentable?
I'm building a multi-box PIN/OTP input in SwiftUI. In UIKit, I used UITextFieldDelegate to detect backspace presses on an empty field to move focus backward. SwiftUI’s .onChange(of: text) only triggers when text is actually deleted, completely missing backspaces on an already empty field. Is there a pure SwiftUI way to handle this now, or are we still forced to wrap UITextField via UIViewRepresentable?
1
0
52
2d
Source view disappearing when interrupting a zoom navigation transition
When I use the .zoom transition in a navigation stack, I get a glitch when interrupting the animation by swiping back before it completes. When doing this, the source view disappears. I can still tap it to trigger the navigation again, but its not visible on screen. This seems to be a regression in iOS 26, as it works as expected when testing on iOS 18. Has someone else seen this issue and found a workaround? Is it possible to disable interrupting the transition? Filed a feedback on the issue FB19601591 Screen recording: https://share.icloud.com/photos/04cio3fEcbR6u64PAgxuS2CLQ Example code @State var showDetail = false @Namespace var namespace var body: some View { NavigationStack { ScrollView { showDetailButton } .navigationTitle("Title") .navigationBarTitleDisplayMode(.inline) .navigationDestination(isPresented: $showDetail) { Text("Detail") .navigationTransition(.zoom(sourceID: "zoom", in: namespace)) } } } var showDetailButton: some View { Button { showDetail = true } label: { Text("Show detail") .padding() .background(.green) .matchedTransitionSource(id: "zoom", in: namespace) } } }
Topic: UI Frameworks SubTopic: SwiftUI
20
25
2.4k
3d
iOS 27 beta 1: .scrollEdgeEffectStyle(.soft) renders fully transparent above safeAreaBar
Feedback ID: FB23086400 On iOS 27 beta 1, .scrollEdgeEffectStyle(.soft, for: .top) on a List underneath a custom .safeAreaBar(edge: .top) no longer renders the progressive fade-blur. The top edge is fully transparent — scrolled rows pass under the bar with no visual treatment at all, as if scrollEdgeEffectDisabled() had been applied. What I've verified so far: .hard renders correctly in the exact same hierarchy; only .soft is affected. The same binary works correctly on iOS 26.x Xcode preview. I'm building with Xcode 26.3 (iOS 26 SDK). Minimal reproduction: import SwiftUI struct EdgeEffectRepro: View { enum Style: String, CaseIterable, Identifiable { case automatic, soft, hard var id: Self { self } var value: ScrollEdgeEffectStyle { switch self { case .automatic: .automatic case .soft: .soft case .hard: .hard } } } @State private var style: Style = .soft @State private var useSystemBarOnly = false var body: some View { NavigationStack { List(0..<60, id: \.self) { i in Text("Row \(i)") .frame(maxWidth: .infinity, alignment: .leading) .listRowBackground( i.isMultiple(of: 2) ? Color.orange.opacity(0.45) : Color.teal.opacity(0.45) ) } .scrollIndicators(.hidden) .scrollEdgeEffectStyle(style.value, for: .top) .safeAreaBar(edge: .top) { if !useSystemBarOnly { VStack(spacing: 8) { HStack { Text("Custom Top Bar") .font(.system(size: 28, weight: .bold)) Spacer() } HStack { Text("Second row (e.g. date range picker)") .font(.caption) .foregroundStyle(.secondary) Spacer() } } .padding(.horizontal) } } .safeAreaInset(edge: .bottom) { VStack(spacing: 8) { Picker("Edge effect style", selection: $style) { ForEach(Style.allCases) { Text($0.rawValue).tag($0) } } .pickerStyle(.segmented) Toggle("System bar only (control group)", isOn: $useSystemBarOnly) .font(.caption) } .padding() .background(.regularMaterial) } .navigationTitle("EdgeEffect Repro") .navigationBarTitleDisplayMode(.inline) } } } Steps: run on iOS 27 beta 1, set the picker to soft, scroll rows under the bar. Expected: fade-blur as on iOS 26. Actual: fully transparent. Switch to hard: renders fine.
0
1
85
3d
Is there a better way to hide a view in a custom Layout other than placing it off-screen?
I have a custom Layout that places a number of labels for a cell footer in a certain way based on the available width that needs to conditionally hide those views that do not entirely fit anymore (based on some priorities I specify). Currently I simply move the subviews that do not fit anymore off-screen and use clipping to hide them outside the layout, as I did not find an "official" way to hide / exclude a subview from a Layout. Does anyone know a better / nicer way to do this in SwiftUI?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
20
3d
Pass data to an @Observable model
Overview I have a navigation split view. The detail view contains a model now this model depends on id from the parent view. Questions How can I pass data from the parent view and yet create the view in the detail view? Or should I be pass the model from the parent view, but the problem is the parent view needs to persist model. Or is there a better approach?
0
0
29
3d
AsyncRenderer stack limit
We've been getting stack overflows in code we don't control, in the background AsyncRenderer thread in a chain of calls to updateInheritedViewAsync. But the stack is less than 200 calls deep, presumably because it's a background thread with a smaller stack limit. Is it possible to adjust AsyncRenderer's stack limit? Or otherwise, what limits should we be aware of to prevent running into this issue? com.apple.SwiftUI.AsyncRenderer: EXC_BAD_ACCESS (code=2, address=0x16f5ebe30) #0 0x000000019c6b4460 in function signature specialization <Arg[3] = Dead> of static SwiftUI.DisplayList.ViewUpdater.Model.merge(item: inout SwiftUI.DisplayList.Item, index: SwiftUI.DisplayList.Index, into: inout SwiftUI.DisplayList.ViewUpdater.Model.State) -> SwiftUI.DisplayList.ViewUpdater.Model.MergedViewRequirements () #1 0x000000019c7c2850 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #2 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #3 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #4 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () ... #147 0x000000019c7c364c in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #148 0x000000019c7c2074 in SwiftUI.DisplayList.ViewUpdater.updateAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldList: SwiftUI.DisplayList, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newList: SwiftUI.DisplayList, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #149 0x000000019c7c1a78 in renderAsync () #150 0x000000019c60fc68 in renderDisplayList () #151 0x000000019c612094 in protocol witness for SwiftUI.ViewGraphRenderHost.renderDisplayList(_: SwiftUI.DisplayList, asynchronously: Swift.Bool, time: SwiftUI.Time, nextTime: SwiftUI.Time, targetTimestamp: Swift.Optional<SwiftUI.Time>, version: SwiftUI.DisplayList.Version, maxVersion: SwiftUI.DisplayList.Version) -> SwiftUI.Time in conformance SwiftUI.ViewGraph : SwiftUI.ViewGraphRenderHost in SwiftUI () #152 0x000000019c7c0dd0 in renderAsync () #153 0x000000019c7be6c8 in SwiftUI.ViewGraphHost.displayLinkTimer(timestamp: SwiftUI.Time, targetTimestamp: SwiftUI.Time, isAsyncThread: Swift.Bool) -> () () #154 0x000000019c7beab8 in SwiftUI.ViewGraphDisplayLink.displayLinkTimer(__C.CADisplayLink) -> () () #155 0x000000019c7be5a8 in @objc SwiftUI.ViewGraphDisplayLink.displayLinkTimer(__C.CADisplayLink) -> () () #156 0x0000000192fdbb24 in CA::Display::DisplayLinkItem::dispatch_ () #157 0x0000000192fb9164 in CA::Display::DisplayLink::dispatch_items () #158 0x0000000192f91870 in display_timer_callback () #159 0x000000019256d4cc in __CFMachPortPerform () #160 0x000000019259d0b0 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ () #161 0x000000019259cfd8 in __CFRunLoopDoSource1 () #162 0x0000000192574c1c in __CFRunLoopRun () #163 0x0000000192573a6c in _CFRunLoopRunSpecificWithOptions () #164 0x0000000190533f54 in -[NSRunLoop(NSRunLoop) runMode:beforeDate:] () #165 0x000000018fb9a51c in -[NSRunLoop(NSRunLoop) run] () #166 0x000000019c7cd5b0 in function signature specialization <Arg[1] = Dead> of static SwiftUI.ViewGraphDisplayLink.asyncThread(arg: Swift.Optional<Any>) -> () () #167 0x000000019c7cd288 in @objc static SwiftUI.ViewGraphDisplayLink.asyncThread(arg: Swift.Optional<Any>) -> () () #168 0x000000018fbf321c in __NSThread__start__ () #169 0x00000001ef0d044c in _pthread_start ()
Topic: UI Frameworks SubTopic: SwiftUI
2
1
101
3d
OS27 LazyVGrid hops like crazy on scroll up.
I’m not sure if this is a ”care later in the summer” situation, but on beta 1, with an .adaptive Grid Item, a scrolling LazyVGrid will hop and “bounce” when scrolling back up from the bottom of the grid. I can see the scrollbar visibly hopping as item views are re-created. Anyone else seeing this?
Replies
1
Boosts
1
Views
37
Activity
14h
Menu in the bottom bar flies to the top of the screen
I have a Menu in a Toolbar (specifically, the .bottomBar). If I open the menu quickly after it appears (within a few seconds), it flies to the top of the screen. I've created a minimum woking example below. This appears to be a pretty glaring iOS 26 bug that has been present since the early betas, but I can't seem to find much discussion about it (apart from this post from 8 months ago), so I'm wondering if I might be doing something wrong. Or maybe someone managed to figure out a workaround. If the Menu is very simple (just Text items), it seems to be okay. But if the Menu is even slightly complex (e.g. includes icons), then it exhibits the flying behavior. I've also been able to reproduce this bug under different types of navigation component (e.g. NavigationSplitView). I'm seeing this behavior in the current version of iOS (26.2.1), both on device and in the simulator. MWE struct ContentView: View { var body: some View { NavigationStack { VStack { NavigationLink("Go to Detail") { DetailView() } } .navigationTitle("Root") } } } struct DetailView: View { var body: some View { VStack { Text("Detail View") } .navigationTitle("Detail") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .bottomBar) { Menu { Button { } label: { Label("Delete", systemImage: "trash") } } label: { Image(systemName: "ellipsis.circle") } } } } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
3
Boosts
1
Views
239
Activity
17h
NavigationSplitView no longer pops back to the root view when selection = nil in iOS 26.4 (with a nested TabView)
In iOS 26.4 (iPhone, not iPad), when a NavigationSplitView is combined with a nested TabView, it no longer pops back to the root sidebar view when the List selection is set to nil. This has been working fine for at least a few years, but has just stopped working in iOS 26.4. Here's a minimal working example: import SwiftUI struct ContentView: View { @State var articles: [Article] = [Article(articleTitle: "Dog"), Article(articleTitle: "Cat"), Article(articleTitle: "Mouse")] @State private var selectedArticle: Article? = nil var body: some View { NavigationSplitView { TabView { Tab { List(articles, selection: $selectedArticle) { article in Button { selectedArticle = article } label: { Text(article.title) } } } label: { Label("Explore", systemImage: "binoculars") } } } detail: { Group { if let selectedArticle { Text(selectedArticle.title) } else { Text("No selected article") } } .navigationBarBackButtonHidden(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", systemImage: "xmark") { selectedArticle = nil } } } } } } struct Article: Identifiable, Hashable { let id: String let title: String init(articleTitle: String) { self.id = articleTitle self.title = articleTitle } } First, I'm aware that nesting a TabView inside a NavigationSplitView is frowned upon: Apple seems to prefer NavigationSplitView nested inside a Tab. However, for my app, that leads to a very confusing user experience. Users quickly get lost because they end up with different articles open in different tabs and it doesn't align well with my core distinction between two "modes": article selection mode and article reading mode. When the user is in article selection mode (sidebar view), they can pick between different ways of selecting an article (Explore, Bookmarks, History, Search), which are implemented as "tabs". When they pick an article from any tab they jump into article reading mode (the detail view). Second, I'm using .navigationBarBackButtonHidden(true) to remove the auto back button that pops back to the sidebar view. This button does still work in iOS 26.4, even with the nested TabView. However, I can't use the auto back button because my detail view is actually a WebView with its own back/forward logic and UI. Therefore, I need a separate close button to exit from the detail view. My close button sets selectedArticle to nil, which (pre-iOS 26.4) would trigger the NavigationSplitView to pop back to the sidebar view. For some reason, in iOS 26.4 the NavigationSplitView doesn't seem to bind correctly to the List's selection parameter, specifically when there's a TabView nested between them. Or, rather, it binds, but fails to pop back when selection becomes nil. One option is to replace NavigationSplitView with NavigationStack (on iPhone). NavigationStack still works with a nested TabView, but it creates other downstream issues for me (as well as forcing me to branch for iPhone and iPad), so I'd prefer to continue using NavigationSplitView. Does anyone have any ideas about how to work around this problem? Is there some way of explicitly telling NavigationSplitView to pop back to the sidebar view on iPhone? (I've tried setting the column visibility but nothing seems to work). Thanks for any help!
Replies
2
Boosts
1
Views
222
Activity
17h
MapKit MapCamera
SwiftUI Map with MapCamera jerks on every GPS update instead of animating smoothly I'm trying to make camera to follow the user smoothly during navigation using MapCamera with heading and pitch, similar to Apple Maps or Google Maps. The camera updates on every GPS tick but instead of animating smoothly between positions it jerks , it snaps to the new position, pauses, snaps again, pauses...terrible UX. The blue user location (UserAnnotation) puck moves completely smoothly. Only the camera jerks I have tried all sort of animations and interpolation you may think of. Something is just not right, must be something missing from the puzzle. I have prepared a minimal reproducible example so you can copy and paste the only thing needed is to add the Privacy - Location When In Use Usage Description Run in Simulator, go to Features > Location > Freeway Drive and tap on Track then you'll notice how camera is following then stop then following and stops again Don't bother using AI, he has no clue what's this all about. I also went through docs to find anything useful like a magic modifier, but no joy Here is a video hosted online as well: [https://streamable.com/ear9cv] And a code snippet copy paste import MapKit import CoreLocation // You'll only need to add Privacy - Location When In Use Usage Description to the Info tab struct ContentView: View { @State private var locationManager = LocationManagerDelegate() @State private var cameraPosition: MapCameraPosition = .userLocation(followsHeading: false, fallback: .automatic) @State private var isTracking: Bool = false @State private var lastKnownHeading: Double = 0 var body: some View { Map(position: $cameraPosition) { UserAnnotation() } .onChange(of: locationManager.location) { _, location in guard isTracking, let location else { return } withAnimation(.linear(duration: 0.5)) { cameraPosition = .camera(MapCamera( centerCoordinate: location.coordinate, distance: 1000, heading: location.course, pitch: 60 )) } } .safeAreaInset(edge: .bottom) { // Added to the safeAreaInset to keep the Apple Logo visible Button("Track") { isTracking.toggle() locationManager.requestPermission() locationManager.startNavigating() } .buttonStyle(.glassProminent) .buttonSizing(.flexible) .controlSize(.extraLarge) .padding(.horizontal) } } } @MainActor @Observable final class LocationManagerDelegate: NSObject, CLLocationManagerDelegate { var location: CLLocation? var authorizationStatus: CLAuthorizationStatus = .notDetermined let manager = CLLocationManager() private var liveUpdateTask: Task<Void, Never>? override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation authorizationStatus = manager.authorizationStatus } func requestPermission() { manager.requestWhenInUseAuthorization() } func startNavigating() { liveUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.automotiveNavigation) { guard let newLocation = update.location else { continue } self.location = newLocation } } catch { print("Live updates error: \(error)") } } } func stopNavigating() { liveUpdateTask?.cancel() liveUpdateTask = nil manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus } }
Replies
0
Boosts
0
Views
17
Activity
18h
Xcode video rendering performance
video-probe test [object Object]
Topic: UI Frameworks SubTopic: SwiftUI
Replies
0
Boosts
0
Views
12
Activity
19h
How to build a picker wheel similar as the Calendar App?
How to build the below UI using SwiftUI? I tried to use Picker with wheel style, but it is not the same as the screenshot. The screenshot came from the iOS built-in calendar app. Add a new calendar event Click "Repeat" Choose "Custom" Click "Every day" The required picker wheel will be displayed Picker("Every", selection: $interval) { ForEach(1..<366) { interval in Text("\(interval)").tag(interval) } } .pickerStyle(.wheel)
Replies
0
Boosts
0
Views
22
Activity
20h
How do I get SwiftUI to let me determine a custom frame size for NSTextField
I have a NSViewRepresentable that wraps an NSTextField subclass which is displayed as larger than your typical text field. SwiftUI doesn't seem to allow me to set the size of the view when the underlying is an NSTextField. It forces it as a single line field. I've tried both setting the frame on creation as well as using SwiftUI .frame(width:height:) on the represented view. I always end up with a single line field. struct BigTextField: NSViewRepresentable { @Binding var text: String class Coordinator: NSObject, NSTextFieldDelegate { var parent: BigTextField init(_ parent: BigTextField) { self.parent = parent } func controlTextDidChange(_ obj: Notification) { if let textField = obj.object as? NSTextField { parent.text = textField.stringValue } } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSTextField { //let frame = NSRect(x: 0, y: 0, width: 350, height: 140) //let textField = NSTextField(frame: frame) let textField = NSTextField() textField.isEditable = true textField.isBordered = true textField.isBezeled = true textField.delegate = context.coordinator // Assign the coordinator return textField } func updateNSView(_ nsView: NSTextField, context: Context) { if nsView.stringValue != text { nsView.stringValue = text } } } I've also included the SwiftUI declaration which demonstrates the problem. struct ContentView: View { @State var text : String = "Test string" var body: some View { VStack { BigTextField(text: $text) .frame(width: 350, height: 140) } .padding() } } NSTextField can be any arbitrary frame size. I already do this from AppKit but am trying to adapt this custom field to work within SwiftUI. SwiftUI seems to override the sizing of this NSViewRepresentable that I give it. Am I missing something here? Is there some way to override SwiftUI's sizing behavior? Thank you.
Replies
0
Boosts
0
Views
21
Activity
1d
Back gesture not disabled with navigationBarBackButtonHidden(true) when using .zoom transition
[Submitted as FB22226720] For a NavigationStack destination, applying .navigationBarBackButtonHidden(true) hides the back button and also disables the interactive left-edge back gesture when using the standard push navigation transition. However, when the destination uses .navigationTransition(.zoom), the back button is hidden but the left-edge back gesture is still available—it can still be dismissed even though back is intentionally suppressed. This creates inconsistent behavior between navigation transition styles. navigationBarBackButtonHidden(_:) works with a standard push transition, but not with .navigationTransition(.zoom). In the code below, .interactiveDismissDisabled(true) is also applied as another attempt to suppress the back-swipe gesture, but it has no effect. As a result, there’s currently no clean way to prevent back navigation when using the zoom transition. REPRO STEPS Create an iOS project then replace ContentView with code below, build and run. Leave nav type set to List Push. Open an item. Verify there is no back button, then try the left-edge back gesture. Return to the root view. Change nav type to Grid Zoom. Open an item. Verify there is no back button, then try the left-edge back gesture. ACTUAL In List Push mode, the left-edge back gesture is prevented. In Grid Zoom mode, the back button is hidden, but the left-edge back gesture still works and returns to the previous view. EXPECTED Behavior should be consistent across navigation transition styles. If this configuration is meant to suppress interactive backward navigation for a destination, it should also suppress the left-edge back gesture when using .navigationTransition(.zoom). SCREEN RECORDING SAMPLE CODE struct ContentView: View { private enum NavigationMode: String, CaseIterable { case listPush = "List Push" case gridZoom = "Grid Zoom" } @Namespace private var namespace @State private var navigationMode: NavigationMode = .listPush private let colors: [Color] = [.red, .blue] var body: some View { NavigationStack { VStack(spacing: 16) { Picker("Navigation Type", selection: $navigationMode) { ForEach(NavigationMode.allCases, id: \.self) { mode in Text(mode.rawValue).tag(mode) } } .pickerStyle(.segmented) if navigationMode == .gridZoom { HStack { ForEach(colors.indices, id: \.self) { index in NavigationLink(value: index) { VStack { RoundedRectangle(cornerRadius: 14) .fill(colors[index]) .frame(height: 120) Text("Grid Item \(index + 1)") .font(.subheadline.weight(.medium)) } .padding(12) .frame(maxWidth: .infinity) .background(.quaternary.opacity(0.25), in: RoundedRectangle(cornerRadius: 16)) .matchedTransitionSource(id: index, in: namespace) } .buttonStyle(.plain) } } } else { ForEach(colors.indices, id: \.self) { index in NavigationLink(value: index) { HStack { Circle() .fill(colors[index]) .frame(width: 24, height: 24) Text("List Item \(index + 1)") Spacer() Image(systemName: "chevron.right") .foregroundStyle(.secondary) } .padding() .background(.quaternary.opacity(0.25), in: RoundedRectangle(cornerRadius: 12)) } .buttonStyle(.plain) } } Spacer() } .padding(20) .navigationTitle("Prevent Back Swipe") .navigationSubtitle("Compare Grid Zoom vs List Push") .navigationDestination(for: Int.self) { index in if navigationMode == .gridZoom { DetailView(color: colors[index]) .navigationTransition(.zoom(sourceID: index, in: namespace)) } else { DetailView(color: colors[index]) } } } } } private struct DetailView: View { @Environment(\.dismiss) private var dismiss let color: Color var body: some View { ZStack { color.ignoresSafeArea() Text("Try left-edge swipe back") .font(.title.bold()) .multilineTextAlignment(.center) .padding(.horizontal, 24) } .navigationBarBackButtonHidden(true) .interactiveDismissDisabled(true) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Close", action: dismiss.callAsFunction) } } } }
Replies
3
Boosts
0
Views
712
Activity
1d
TextKit 2 + SwiftUI (NSViewRepresentable): NSTextLayoutManager rendering attributes don’t reliably draw/update
I’m embedding an NSTextView (TextKit 2) inside a SwiftUI app using NSViewRepresentable. I’m trying to highlight dynamic subranges (changing as the user types) by providing per-range rendering attributes via NSTextLayoutManager’s rendering-attributes mechanism. The issue: the highlight is unreliable. Often, the highlight doesn’t appear at all even though the delegate/data source is returning attributes for the expected range. Sometimes it appears once, but then it stops updating even when the underlying “highlight range” changes. This feels related to SwiftUI - AppKit layout issue when using NSViewRepresentable (as said in https://developer.apple.com/documentation/swiftui/nsviewrepresentable). What I’ve tried Updating the state that drives the highlight range and invalidating layout fragments / asking for relayout Ensuring all updates happen on the main thread. Calling setNeedsDisplay(_:) on the NSViewRepresentable’s underlying view. Toggling the SwiftUI view identity (e.g. .id(...)) to force reconstruction (works, but too expensive / loses state). Question In a SwiftUI + NSViewRepresentable setup with TextKit 2, what is the correct way to make NSTextLayoutManager re-query and redraw rendering attributes when my highlight ranges change? Is there a recommended invalidation call for TextKit 2 to trigger re-rendering of rendering attributes? Or is this a known limitation when hosting NSTextView inside SwiftUI, where rendering attributes aren’t reliably invalidated? If this approach is fragile, is there a better pattern for dynamic highlights that avoids mutating the attributed string (to prevent layout/scroll jitter)?
Replies
4
Boosts
0
Views
392
Activity
2d
Handling View Creation for Heterogeneous Data
In my project (an Package), I have created an Manager (can be classified as an ViewModel) that will handle state updates throughout the Package Component view: Note: The code is simplified for better understanding and to focus on principles behind things I did. The manager does complex things during state updates. public class ComponentManager: ObservedObject { @Published var rows: [any RowProtocol] = [] func updateState(_ newState: any RowProtocolData, id: String) { guard let index = rows.firstIndex(where: { $0.id == id }) else { return } rows[index].updateState(newState) } func getState(id: String) -> any RowProtocolData? { guard let index = rows.firstIndex(where: { $0.id == id }) else { return nil } return rows[index].state } } The RowProtocol is defined as follows: public protocol RowStateProtocol {} public protocol RowProtocol: Identifiable { associatedtype State: RowStateProtocol associatedtype RowView: View var id: String { get } var state: State { get } func updateState(_ newState: State) @MainActor @ViewBuilder func renderRow() -> RowView } extension RowProtocol { func updateState(_ newState: any RowProtocolData) { guard let newState = newState as? State else { return } self.updateState(newState) } } Then in Component View, I need to render the rows based on the underlying type of the row, this where the renderRow() comes in: struct ComponentView: View { @ObservedObject var manager: ComponentManager var body: some View { List { ForEach(manager.rows, id: \.id) { row in HStack { // This HStack prevent List from initing all rows due to AnyView. AnyView(row.renderRow()) } } } } } The row views will be accepting binding to the state of the row and update their state, let says we have a TextRow and a ToggleRow: struct TextRow: RowProtocol { var id: String var state: TextRowState func updateState(_ newState: TextRowState) { self.state = newState } } struct ToggleRow: RowProtocol { var id: String var state: ToggleRowState func updateState(_ newState: ToggleRowState) { self.state = newState } } In this, offcourse we cannot create an binding directly to the state of the row, since the state are through the manager and the row data won't have access to the manager. So I created an property wrapped that use the closures passed by the manager into environment to create the binding and an view that will give the binding to the content view: extenstion EnvironmentValues { @Entry internal var getState: (String) -> any RowStateProtocol? @Entry internal var updateState: (any RowStateProtocol, String) -> Void } @propertyWrapper struct RowStateBinding<State: RowStateProtocol & Equatable>: DynamicProperty { @Environment(\.getState) private var getState @Environment(\.updateState) private var updateState private let id: String init(id: String) { self.id = id } var wrappedValue: State { get { getState(id) as! State } nonmutating set { if wrappedValue != newValue { // only update for an new change, since set can be triggered for any number of reasons. updateState(newValue, id) } } } var projectedValue: Binding<State> { Binding( get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue } ) } } struct RowStateBindingView<Content: View, State: RowStateProtocol & Equatable>: View { @RowStateBinding<State> private var state: State private let content: (Binding<State>) -> Content init(id: String, @ViewBuilder content: @escaping (Binding<State>) -> Content) { self._state = RowStateBinding(id: id) self.content = content } var body: some View { content($state) } } and in the renderRows: struct TextRowView: View { @Binding var text: TextRowState var body: some View { TextField("Enter text", text: $text.text) } } extension TextRow { func renderRow() -> some View { RowStateBindingView(id: id) { state in TextField("Enter text", text: state.text) } } } struct ToggleRowView: View { @Binding var state: ToggleRowState var body: some View { Toggle("Toggle", isOn: $state.isOn) } } extension ToggleRow { func renderRow() -> some View { RowStateBindingView(id: id) { state in Toggle("Toggle", isOn: state.isOn) } } } This way, I can adopt any view as an row view and most importantly, the view can be completely independent of the manager and used as an standalone view. Also clients of the library can create their own custom rows by just conforming to the RowProtocol and creating the view for it, without worrying about how the state management works. The manager will handle all the state updates. I prefer using stucts over classes for rows and states, since its easier to manage state updates. What do you think about this approach? Do you see any potential issues with this? Is there a better way to achieve this?
Replies
0
Boosts
0
Views
20
Activity
2d
Dynamic Property inplace of onChange, task.
In the recent SwiftUI Group Lab, they mentioned using Dynamic Property instead of onChange, How to do it? Could it used as an actual property type instead of just using in combination with @propertyWrapper
Replies
0
Boosts
0
Views
27
Activity
2d
SwiftUI ​Charts: In iOS 27, annotation overlays exceed the bounds of an annotation
I'm seeing a regression in SwiftUI Charts on iOS 27 beta 1. Any view placed inside a BarMark's overlay annotation no longer receives the size of the parent BarMark. It collapses to zero, so any content sized from geo.size (e.g. a Rectangle meant to fill the bar) renders empty or incorrectly. Expected: The GeometryReader reports the BarMark's rendered width/height, and the Rectangle fills the BarMark (this is the behavior in iOS 26 and earlier). Actual: On iOS 27 beta 1, geo.size is effectively zero, so the overlay content has an extremely small size. I suspect this could be a small bug with the new ContentBuilder / ViewBuilder changes but that's just a hunch. Here's a code sample which reproduces the issue. // MARK: - Mock Data Models struct ScheduleSeries: Identifiable { let id = UUID() let data: [ScheduleItem] } struct ScheduleItem: Identifiable { let id = UUID() let startDate: Date let startHour: Double let endHour: Double let secondaryText: String? } // MARK: - Minimal Reproducible Example struct ContentView: View { // Generate two consecutive days for the mock data let mockSchedule: [ScheduleSeries] = [ ScheduleSeries(data: [ ScheduleItem( startDate: Date(), startHour: 9.0, endHour: 11.5, secondaryText: "Morning Event" ), ScheduleItem( startDate: Calendar.current.date(byAdding: .day, value: 1, to: Date())!, startHour: 13.0, endHour: 16.0, secondaryText: "Afternoon Event" ) ]) ] var body: some View { VStack(alignment: .leading) { Text("FB: Annotation Sizing Bug") .font(.headline) .padding(.bottom, 8) Text("Expected: The gray Rectangle should stretch to fill the BarMark.\nActual: GeometryReader/Annotation fails to size to the parent BarMark.") .font(.caption) .foregroundColor(.secondary) .padding(.bottom) Chart(mockSchedule) { series in ForEach(series.data, id: \.startDate) { element in BarMark( x: .value("Day", element.startDate, unit: .day, calendar: .current), yStart: .value("Start", element.startHour), yEnd: .value("End", element.endHour), width: .ratio(0.99) ) .annotation(position: .overlay, alignment: .topLeading) { item in ZStack { VStack(alignment: .leading, spacing: 0) { // BUG DEMONSTRATION: // This GeometryReader and Rectangle previously filled the BarMark, but in Xcode 27 it does not GeometryReader { geo in Rectangle() .fill(Color.black.opacity(0.15)) .frame(width: geo.size.width, height: geo.size.height) } } .foregroundColor(.white) .font(.caption2) } } } } .chartYScale(domain: 0...24) // Lock the Y-axis to a 24-hour scale } .padding() } } Environment: Xcode 27 beta 1 / iOS 27 beta 1 Reproduces on device and Simulator Worked as expected on iOS 26 and earlier Here's what the issue looks like in our app with zero code changes: iOS 26 iOS 27 I've filed a feedback report (FB23016343) with a sample project attached. Has anyone else hit this, or found a workaround for sizing overlay annotation content to a BarMark in iOS 27? Thanks!
Replies
0
Boosts
0
Views
24
Activity
2d
How to detect backspace in SwiftUI TextField without falling back to UIViewRepresentable?
I'm building a multi-box PIN/OTP input in SwiftUI. In UIKit, I used UITextFieldDelegate to detect backspace presses on an empty field to move focus backward. SwiftUI’s .onChange(of: text) only triggers when text is actually deleted, completely missing backspaces on an already empty field. Is there a pure SwiftUI way to handle this now, or are we still forced to wrap UITextField via UIViewRepresentable?
Replies
1
Boosts
0
Views
52
Activity
2d
Source view disappearing when interrupting a zoom navigation transition
When I use the .zoom transition in a navigation stack, I get a glitch when interrupting the animation by swiping back before it completes. When doing this, the source view disappears. I can still tap it to trigger the navigation again, but its not visible on screen. This seems to be a regression in iOS 26, as it works as expected when testing on iOS 18. Has someone else seen this issue and found a workaround? Is it possible to disable interrupting the transition? Filed a feedback on the issue FB19601591 Screen recording: https://share.icloud.com/photos/04cio3fEcbR6u64PAgxuS2CLQ Example code @State var showDetail = false @Namespace var namespace var body: some View { NavigationStack { ScrollView { showDetailButton } .navigationTitle("Title") .navigationBarTitleDisplayMode(.inline) .navigationDestination(isPresented: $showDetail) { Text("Detail") .navigationTransition(.zoom(sourceID: "zoom", in: namespace)) } } } var showDetailButton: some View { Button { showDetail = true } label: { Text("Show detail") .padding() .background(.green) .matchedTransitionSource(id: "zoom", in: namespace) } } }
Topic: UI Frameworks SubTopic: SwiftUI
Replies
20
Boosts
25
Views
2.4k
Activity
3d
iOS 27 beta 1: .scrollEdgeEffectStyle(.soft) renders fully transparent above safeAreaBar
Feedback ID: FB23086400 On iOS 27 beta 1, .scrollEdgeEffectStyle(.soft, for: .top) on a List underneath a custom .safeAreaBar(edge: .top) no longer renders the progressive fade-blur. The top edge is fully transparent — scrolled rows pass under the bar with no visual treatment at all, as if scrollEdgeEffectDisabled() had been applied. What I've verified so far: .hard renders correctly in the exact same hierarchy; only .soft is affected. The same binary works correctly on iOS 26.x Xcode preview. I'm building with Xcode 26.3 (iOS 26 SDK). Minimal reproduction: import SwiftUI struct EdgeEffectRepro: View { enum Style: String, CaseIterable, Identifiable { case automatic, soft, hard var id: Self { self } var value: ScrollEdgeEffectStyle { switch self { case .automatic: .automatic case .soft: .soft case .hard: .hard } } } @State private var style: Style = .soft @State private var useSystemBarOnly = false var body: some View { NavigationStack { List(0..<60, id: \.self) { i in Text("Row \(i)") .frame(maxWidth: .infinity, alignment: .leading) .listRowBackground( i.isMultiple(of: 2) ? Color.orange.opacity(0.45) : Color.teal.opacity(0.45) ) } .scrollIndicators(.hidden) .scrollEdgeEffectStyle(style.value, for: .top) .safeAreaBar(edge: .top) { if !useSystemBarOnly { VStack(spacing: 8) { HStack { Text("Custom Top Bar") .font(.system(size: 28, weight: .bold)) Spacer() } HStack { Text("Second row (e.g. date range picker)") .font(.caption) .foregroundStyle(.secondary) Spacer() } } .padding(.horizontal) } } .safeAreaInset(edge: .bottom) { VStack(spacing: 8) { Picker("Edge effect style", selection: $style) { ForEach(Style.allCases) { Text($0.rawValue).tag($0) } } .pickerStyle(.segmented) Toggle("System bar only (control group)", isOn: $useSystemBarOnly) .font(.caption) } .padding() .background(.regularMaterial) } .navigationTitle("EdgeEffect Repro") .navigationBarTitleDisplayMode(.inline) } } } Steps: run on iOS 27 beta 1, set the picker to soft, scroll rows under the bar. Expected: fade-blur as on iOS 26. Actual: fully transparent. Switch to hard: renders fine.
Replies
0
Boosts
1
Views
85
Activity
3d
Is there a better way to hide a view in a custom Layout other than placing it off-screen?
I have a custom Layout that places a number of labels for a cell footer in a certain way based on the available width that needs to conditionally hide those views that do not entirely fit anymore (based on some priorities I specify). Currently I simply move the subviews that do not fit anymore off-screen and use clipping to hide them outside the layout, as I did not find an "official" way to hide / exclude a subview from a Layout. Does anyone know a better / nicer way to do this in SwiftUI?
Topic: UI Frameworks SubTopic: SwiftUI
Replies
0
Boosts
0
Views
20
Activity
3d
onChange(of:initial:_:) changes when same value assigned
Overview When calling onChange(of:initial:_:) with initial as true, closure called even when the value assigned is the same as previous value (not just the first time, subsequently too). However when initial value is false it is called only when value changes. Questions Is this a bug? Am I missing something?
Replies
0
Boosts
0
Views
27
Activity
3d
Pass data to an @Observable model
Overview I have a navigation split view. The detail view contains a model now this model depends on id from the parent view. Questions How can I pass data from the parent view and yet create the view in the detail view? Or should I be pass the model from the parent view, but the problem is the parent view needs to persist model. Or is there a better approach?
Replies
0
Boosts
0
Views
29
Activity
3d
about presentationDetents modifier
How do I make the sheet occupy the full screen width and bottom when I customize the height of the sheet using presentationDetents?
Replies
1
Boosts
0
Views
41
Activity
3d
AsyncRenderer stack limit
We've been getting stack overflows in code we don't control, in the background AsyncRenderer thread in a chain of calls to updateInheritedViewAsync. But the stack is less than 200 calls deep, presumably because it's a background thread with a smaller stack limit. Is it possible to adjust AsyncRenderer's stack limit? Or otherwise, what limits should we be aware of to prevent running into this issue? com.apple.SwiftUI.AsyncRenderer: EXC_BAD_ACCESS (code=2, address=0x16f5ebe30) #0 0x000000019c6b4460 in function signature specialization <Arg[3] = Dead> of static SwiftUI.DisplayList.ViewUpdater.Model.merge(item: inout SwiftUI.DisplayList.Item, index: SwiftUI.DisplayList.Index, into: inout SwiftUI.DisplayList.ViewUpdater.Model.State) -> SwiftUI.DisplayList.ViewUpdater.Model.MergedViewRequirements () #1 0x000000019c7c2850 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #2 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #3 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #4 0x000000019c7c3ef0 in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () ... #147 0x000000019c7c364c in SwiftUI.DisplayList.ViewUpdater.updateInheritedViewAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldItem: SwiftUI.DisplayList.Item, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newItem: SwiftUI.DisplayList.Item, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #148 0x000000019c7c2074 in SwiftUI.DisplayList.ViewUpdater.updateAsync(platform: SwiftUI.DisplayList.ViewUpdater.Platform, oldList: SwiftUI.DisplayList, oldParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>, newList: SwiftUI.DisplayList, newParentState: Swift.UnsafePointer<SwiftUI.DisplayList.ViewUpdater.Model.State>) -> Swift.Optional<SwiftUI.Time> () #149 0x000000019c7c1a78 in renderAsync () #150 0x000000019c60fc68 in renderDisplayList () #151 0x000000019c612094 in protocol witness for SwiftUI.ViewGraphRenderHost.renderDisplayList(_: SwiftUI.DisplayList, asynchronously: Swift.Bool, time: SwiftUI.Time, nextTime: SwiftUI.Time, targetTimestamp: Swift.Optional<SwiftUI.Time>, version: SwiftUI.DisplayList.Version, maxVersion: SwiftUI.DisplayList.Version) -> SwiftUI.Time in conformance SwiftUI.ViewGraph : SwiftUI.ViewGraphRenderHost in SwiftUI () #152 0x000000019c7c0dd0 in renderAsync () #153 0x000000019c7be6c8 in SwiftUI.ViewGraphHost.displayLinkTimer(timestamp: SwiftUI.Time, targetTimestamp: SwiftUI.Time, isAsyncThread: Swift.Bool) -> () () #154 0x000000019c7beab8 in SwiftUI.ViewGraphDisplayLink.displayLinkTimer(__C.CADisplayLink) -> () () #155 0x000000019c7be5a8 in @objc SwiftUI.ViewGraphDisplayLink.displayLinkTimer(__C.CADisplayLink) -> () () #156 0x0000000192fdbb24 in CA::Display::DisplayLinkItem::dispatch_ () #157 0x0000000192fb9164 in CA::Display::DisplayLink::dispatch_items () #158 0x0000000192f91870 in display_timer_callback () #159 0x000000019256d4cc in __CFMachPortPerform () #160 0x000000019259d0b0 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ () #161 0x000000019259cfd8 in __CFRunLoopDoSource1 () #162 0x0000000192574c1c in __CFRunLoopRun () #163 0x0000000192573a6c in _CFRunLoopRunSpecificWithOptions () #164 0x0000000190533f54 in -[NSRunLoop(NSRunLoop) runMode:beforeDate:] () #165 0x000000018fb9a51c in -[NSRunLoop(NSRunLoop) run] () #166 0x000000019c7cd5b0 in function signature specialization <Arg[1] = Dead> of static SwiftUI.ViewGraphDisplayLink.asyncThread(arg: Swift.Optional<Any>) -> () () #167 0x000000019c7cd288 in @objc static SwiftUI.ViewGraphDisplayLink.asyncThread(arg: Swift.Optional<Any>) -> () () #168 0x000000018fbf321c in __NSThread__start__ () #169 0x00000001ef0d044c in _pthread_start ()
Topic: UI Frameworks SubTopic: SwiftUI
Replies
2
Boosts
1
Views
101
Activity
3d