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

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

App issues with battery icons after upgrading to iOS 27.2.1
My app displays a battery icon using the SF Symbols library. After upgrading my iPhone from iOS 27 to 27.2.1, the battery icon is not displayed correctly anymore as the foreground colours are being applied differently. It seems that the primary and secondary foreground styles are swapped. Also it seems that the 100% icon now only applies the primary style. I created a small example that shows my issue. Here is a comparison from an iPhone Duo simulator running iOS 27.1, and my iPhone running iOS 27.3: As you can see, the colours are now swapped for 25%, 59%, and 75%, and the full icon only has only one colour with no outline. So my question is: Is this expected/intentional, and if so, am I expected to just work around it? --- ### Example code: ```swift struct ContentView: View { var body: some View { VStack { Image(systemName: "battery.0percent") .foregroundStyle(.green, .red) Image(systemName: "battery.25percent") .foregroundStyle(.green, .red) Image(systemName: "battery.50percent") .foregroundStyle(.green, .red) Image(systemName: "battery.75percent") .foregroundStyle(.green, .red) Image(systemName: "battery.100percent") .foregroundStyle(.green, .red) } } } #Preview { ContentView() } ```
0
0
145
8h
SwiftUI TabView with a .prominent tab exhibits unexpected rendering behavior during iPhone Duo display transitions
Hi Apple Support Team, I would like to report an iPhone Duo-specific regression that appears in iOS 27.2.1. The same application behaves correctly on iOS 27.1, and I have been able to reproduce the issue consistently using a minimal sample application. When running the application on iPhone Duo, transitioning from the outer display to the inner display while the device is opened in landscape orientation results in unexpected UI rendering. Specifically, a large arc-shaped visual element associated with a tab configured with the .prominent role appears on screen after the transition. In addition to the rendering issue, we have observed unexpected UI presentation behavior during these display transitions when a tab is assigned the .prominent role. The issue appears to be tied to the .prominent tab role. When all tabs use the default role, the application behaves as expected and neither the rendering issue nor the unexpected UI behavior is observed. A sample application reproducing the issue is attached. Steps to Reproduce Launch the attached sample application on iPhone Duo running iOS 27.2.1. Ensure that one of the tabs is configured with the .prominent role. Start on the outer display. Open the device and transition to the inner display in landscape orientation. Observe the UI during and after the transition. Expected Result TabView should transition cleanly between the outer and inner displays without rendering artifacts or unexpected UI behavior. Actual Result A large arc-shaped visual artifact appears on screen. Unexpected view presentation behavior may occur during the display transition. Multiple animation- and transform-related warnings are logged. // Attached run time logs. Additional Notes Reproducible in both our production application and the attached sample application. The issue appears to be tied to SwiftUI TabView when a tab is assigned the .prominent role. The issue was not observed on iOS 27.1. The issue occurs during transitions between the outer and inner displays on iPhone Duo. Removing the .prominent role eliminates the issue. Could you please let us know whether this is a known issue with SwiftUI TabView and .prominent tabs during iPhone Duo display transitions on iOS 27.2.1? If there is an existing Feedback report, Apple Developer Forums discussion, internal tracking issue, or recommended workaround, we would greatly appreciate any guidance. Screenshots and a sample project are attached. Thank you for your time and assistance. Please let me know if any additional diagnostics, sysdiagnose captures, logs, or sample projects would be helpful. Best regards, Manish
1
0
169
9h
Regression: AxisValueLabel multiLabelAlignment parameter ignored in iOS 27
Hello Apple SwiftUI / Swift Charts Engineering Team, I am writing to report a layout regression regarding Swift Charts in iOS 27. The multiLabelAlignment property on AxisValueLabel has stopped working as expected, whereas it functions perfectly in iOS 26. Bug Description: When configuring custom string values within AxisMarks using AxisValueLabel with multiLabelAlignment: .trailing, the alignment configuration is completely ignored on iOS 27. Labels fail to align text properly to the trailing edge, causing rendering layout issues for multi-line or custom text labels on the Y-axis. This exact same implementation compiles and aligns correctly on iOS 26. Code Snippet to Reproduce: swift struct YAxisAlignmentBugView: View { // data points to render the chart frame let data = [(date: Date(), revenue: 3000.0), (date: Date().addingTimeInterval(10000), revenue: 4000.0)] var body: some View { Chart(data, id: .date) { item in LineMark(x: .value("Date", item.date), y: .value("Revenue", item.revenue)) } .frame(height: 300) .padding() .chartYAxis { AxisMarks(preset: .aligned, position: .trailing, values: [12.0, 600.0, 3000.0, 6000.0]) { value in if let revenue = value.as(Double.self) { // BUG: multiLabelAlignment: .trailing is completely ignored on iOS 27 AxisValueLabel("y-(Int(revenue))", anchor: .leading, multiLabelAlignment: .trailing) } } } } } Steps to Reproduce: Render a Swift Chart containing a .chartYAxis configuration with position: .trailing. Pass a string directly using AxisValueLabel(customText, anchor: .leading, multiLabelAlignment: .trailing). Run the application on an iOS 26 simulator (text aligns properly to the trailing edge). Run the identical application code on an iOS 27 simulator. Expected Behavior: The text inside the AxisValueLabel should honor the multiLabelAlignment: .trailing parameter and align the text strings flush right. Actual Behavior: The multiLabelAlignment layout modifier is ignored on iOS 27, resulting in unexpected default left-alignment of the text strings. Attachments: I have attached screenshots from the Xcode Simulator demonstrating the regression: Please let me know if you need any further diagnostic details. Best regards, Soumyajit Das
3
0
306
11h
Regression: AxisValueLabel anchor parameter ignores .topLeading on iOS 27
Hello Apple SwiftUI / Swift Charts Engineering Team, I am writing to report a layout regression regarding Swift Charts in iOS 27. The anchor property on AxisValueLabel has stopped honoring the .topLeading layout coordinate, whereas it functions perfectly in iOS 26. Bug Description: To prevent the first label on a bottom X-axis from clipping past the left screen edge, a .topLeading anchor is applied. In iOS 27, this specific anchor alignment is completely ignored. The chart falls back to a standard top-center alignment, causing the initial boundary label to clip off-screen. Core Code Snippet to Reproduce: struct XAxisAnchorBugView: View { let dates = [ Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 1))!, Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 2))! ] var body: some View { Chart(dates, id: .self) { date in LineMark(x: .value("Date", date), y: .value("Value", 100)) } .frame(height: 300) .padding() .chartXAxis { AxisMarks(preset: .aligned, position: .bottom, values: .stride(by: .day, count: 1)) { value in AxisTick() let currentAnchor: UnitPoint = { guard let currentDate = value.as(Date.self) else { return .top } // BUG: .topLeading layout anchor parameter is completely ignored on iOS 27 return (currentDate == dates.first) ? .topLeading : .top }() AxisValueLabel(format: .dateTime.month(.abbreviated).day(), anchor: currentAnchor) } } } } Steps to Reproduce: Render an X-axis with a .bottom position. Assign anchor: .topLeading strictly to the first axis element's label. Run on an iOS 26 simulator (the first label anchors its top-left corner correctly, preventing edge clipping). Run on an iOS 27 simulator (the .topLeading anchor is ignored, reverting to standard top-center alignment). Expected Behavior: AxisValueLabel should position its layout bounding box using the .topLeading anchor point when specified. Actual Behavior: The layout engine ignores the .topLeading parameter on iOS 27, causing the boundary text to shift left and clip. Attachments: I have attached Xcode Simulator screenshots demonstrating this regression: Best regards, Soumyajit Das
3
0
329
12h
iPhone Duo Unfolded Safe Areas
Hi, my app is currently built on Xcode 27.1 I am working on upgrading to Xcode 27.2 We have a regression issue whereby, the top safeArea is 82 despite the vertical bar being opted in and active. This only happens on unfolded landscape. Our right safeArea is 0 for the window and is 84 for the view safeArea. Both window and view safeAreas have the top safe area of 82 though. We would like to know what could be the cause behind the top safeArea being activated. Note: this is not an issue for iOS 27.1
2
0
187
1d
SwiftUI Architecture Guide
Application Types Applications are divided into Document-based and Library-based. A document-based application stores user data in individual, standalone files. Users manually name and organize those files in a local system or synced cloud storage such as iCloud. The software typically opens multiple windows for different projects. This framing is for standalone, complex files that need to be shared, exported, or handled independently. A library-based application manages data in one unified, central repository, locally or through remote cloud databases. Spotify, Netflix, and Notion are the examples shown. The file system is hidden; updates are saved automatically in real time; and a single window supports browsing, search, and access to the synchronized data collection from any device. Model Types Four model types: Data, Domain, Application, and Presentation. Apple Platforms In Apple MVC (AppKit / UIKit), the model branches to Data, Domain, and Presentation. In SwiftUI, Model branches to Data and Domain. Project Structure SwiftUI App Folders Swift Package Folders App Modularization Not every module in a large application needs to be extracted into a separate framework or Swift Package. Logical modularization can also be achieved through a well-organized folder structure within the main project. Introduce separate packages or frameworks only when there is a clear benefit, such as independent reuse, distribution, build isolation or ownership. Avoid unnecessary project and dependency management overhead. State Management & Data Flow Source of truth is “a key concept in SwiftUI”: a single place to store a piece of data, with everywhere else reading the same piece of data. Environment is SwiftUI’s native dependency-injection mechanism. It allows shared dependencies, domain models, and services to be injected at the appropriate view-hierarchy level and accessed where needed without explicit parameter passing or unnecessary coupling. It is described as a tool for managing dependencies and sharing state across the view hierarchy. Domain Model Ownership Domain Models should be owned by the highest relevant SwiftUI view in the hierarchy that defines their context and lifecycle. NavigationStack owns the Domain Models for its navigation context and makes them available to descendant views through @Environment. When a NavigationStack is embedded in a TabView or NavigationSplitView, ownership moves up to the TabView or NavigationSplitView so the models can be shared across tabs or split views. The stated result is clear ownership scope, sharing where needed, and isolation between independent navigation contexts. Previews & UI Testing Environment injection makes SwiftUI Previews and UI Tests easier to configure by allowing real Domain Models to be replaced with mock or dummy instances. Views can be tested independently with controlled data and predictable states, without requiring real services, network requests, or application setup. Domain and Data Model Examples For a library-based app with remote data. Additional Domain Model Examples E-commerce Catalog, ShoppingCart, OrderHistory, Wishlist Banking MyAccounts, MyCards, MyTransactions, MyInvestments Social Network Feed, Conversations, Notifications, Friends Healthcare MyAppointments, MedicalHistory, Prescriptions, MyHealth Education Courses, MyCourses, Assignments, MyGrades, LearningProgress Real Estate PropertyCatalog, MyProperties, Favorites, Appointments Hotel Booking Destinations, Search, MyBookings, TravelHistory Food Delivery RestaurantCatalog, ShoppingCart, MyOrders, DeliveryTracking Project Management Projects, MyTasks, TeamMembers, Notifications Insurance MyPolicies, MyClaims, Coverage, Documents Smart Home MyHomes, Devices, Automations, EnergyUsage Fitness MyPlans, MyProgress, MyGoals, WorkoutHistory Other Search, Dashboard, Favorites, Notifications, Settings, ActivityHistory, Recommendations, Subscription, DocumentLibrary ViewModel? - MVVM In SwiftUI, the View encapsulates the UI content (body), its state (properties), and its actions or tasks (functions). This is possible because SwiftUI is designed around a declarative, state-driven UI model. In Android and .NET platforms, a separate ViewModel is typically required to hold and manage the View's state. Projects that intoduce ViewModels in SwiftUI add unnecessary architectural complexity, boilerplate, and code duplication; synchronization issues; unclear state ownership; additional lifecycle management; more abstractions; harder debugging; and increased maintenance, without meaningful benefits over SwiftUI's native state management. In UIKit, introducing a separate ViewModel layer is often unnecessary, as UIViewController already serves as the presentation model, handling presentation logic and coordinating the view. Non-UI responsibilities can be delegated to dedicated ModelControllers or Managers, avoiding unnecessary layers and abstractions. Domain Models vs. ViewModels Domain Models are view-independent, while ViewModels are view-dependent. A ViewModel is tightly coupled to the structure, state, and lifecycle of a specific View. Whenever the View code changes, its ViewModel often requires corresponding coding changes, and vice versa, creating additional maintenance and synchronization overhead. Domain Models, on the other hand, represent application context and business functionality independently of the UI. This separation preserves UI independence and allows the same Domain Models to be shared across different screens and platforms, such as iPhone, iPhone Duo, iPad, and macOS, without duplicating or adapting business logic for each View. This makes Domain Models a more scalable and maintainable approach for modern SwiftUI applications, particularly those targeting multiple screen sizes and platforms.
1
0
246
1d
Accessibility Inspector Element Detection and contrast failures with SwiftUI sheets
I am investigating Accessibility Inspector/XCTest audit results in a SwiftUI app (Target Keeper), without suppressing warnings. Environment: Xcode 27.1 (27A9275), iPadOS 27.0 Simulator, macOS 27.0.1. Debug and Release builds pass. The app uses scalable text and labeled controls. Element Detection / native sheet Main-screen Element Detection passes when the sheet is closed. With a SwiftUI .sheet presented, the iPad audit reports “Potentially inaccessible text”; XCUIAccessibilityAuditIssue.element is nil. Exported Inspector HTML highlights background labels behind/outside the sheet, rather than a foreground control. The separate, data-free SwiftUI application below reproduces the modal-only warning; it links no application modules or persistence. Actual iPad Simulator VoiceOver testing using XCUIDevice.shared.voiceOverService passes forward/backward traversal of the real application's modal controls, without reaching the background labels. This is simulator evidence, not physical-device acceptance. A trial explicit modal container/.isModal trait did not clear the audit and was reverted; no warnings are filtered. Minimal independent app: import SwiftUI @main struct ModalRepro: App { @State private var showing=false private let names=["Vegetables","Protein","Fruit","Dairy","Grains","Healthy Fats"] var body:some Scene {WindowGroup { NavigationStack { VStack(spacing:24) { Button("Nutrition") {}.accessibilityLabel("Choose Page").accessibilityValue("Nutrition") LazyVGrid(columns:[GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())],spacing:40) { ForEach(names,id:\.self) { name in Button {} label: { VStack(spacing:10) { Circle().fill(.blue.opacity(0.3)).frame(width:250,height:250) Text(name).font(.system(size:17)).accessibilityHidden(true) } }.buttonStyle(.plain).accessibilityLabel(name) } } Button("Show modal") {showing=true} }.padding(24).frame(maxWidth:.infinity,maxHeight:.infinity).background(Color.black) }.preferredColorScheme(.dark) .sheet(isPresented:$showing) { NavigationStack { VStack {Text("Foreground content");Button("Close") {showing=false}} .frame(maxWidth:.infinity,maxHeight:.infinity).background(Color.black) .navigationTitle("Modal flow") }.preferredColorScheme(.dark) } }} }In an Xcode UI-test target, launch this app, run try app.performAccessibilityAudit(for: [.elementDetection]), tap “Show modal”, then run the same audit again. The first passes and the second fails. No issue handler ignores failures. Contrast / scrolling — separate unresolved finding All four iPhone combined-audit configurations (portrait/landscape, normal/maximum Dynamic Type) pass in the tested picker state. However, iPad maximum-text combined audits and a separate scrolled iPhone maximum-text landscape contrast audit still fail; we are not calling these resolved. In the scrolled iPhone case, XCTest identifies a count label whose frame is entirely above the visible results viewport. Inspector's exported HTML reports 1.37:1 using #252526 versus #000000; its marked screenshot rectangle overlaps the dark search/header area, not visible count text. Visible sampled labels instead have white or light foregrounds on opaque dark fills (e.g. #FFFFFF/#1C1C1E = 17.01:1; #98989F/#1C1C1E = 5.94:1). These are screenshot core-pixel measurements, not proof every warning is false. We compare ordinary text against 4.5:1 and interactive non-text against 3:1. iPad maximum-text warnings have not yet been matched to an exact visible color pair. Original failures and HTML exports are preserved privately. Questions Is Element Detection expected to inspect background elements behind a presented native SwiftUI sheet? Is this a known tool limitation/framework issue, or does the sample need different semantics? What is the supported way to establish modal accessibility boundaries with SwiftUI sheets, and when should .isModal be added explicitly? How should we distinguish a real contrast defect from clipping, occlusion, translucency, or sampling of an offscreen element? Which Inspector export fields/diagnostics should establish the actual sampled text/background pair? What additional evidence/manual and physical-device tests does Apple recommend before qualifying accessibility when the minimal audit reproduction fails but actual VoiceOver modal focus behaves correctly? We are not asking to waive audits or declare full accessibility from a VoiceOver pass alone. I read Apple's audit guidance and modal trait documentation: https://developer.apple.com/documentation/accessibility/performing-accessibility-audits-for-your-app https://developer.apple.com/documentation/swiftui/accessibilitytraits/ismodal https://developer.apple.com/help/app-store-connect/manage-app-accessibility/sufficient-contrast-evaluation-criteria/ Related discussion https://developer.apple.com/forums/thread/823968 recommends Feedback for a different apparent Dynamic Type false positive; it does not answer these modal/contrast questions. A Feedback draft is prepared but not submitted, so I have no Feedback ID yet. No private data, identifiers, credentials, app containers or confidential application source are included.
2
0
1.2k
1d
SwiftUI custom focusable view cannot acquire focus programmatically on iPad with a hardware keyboard connected
On iPad, a SwiftUI view using .focusable(interactions: .edit) and .focused($isFocused) cannot acquire focus when a hardware keyboard is already connected. Setting isFocused = true from a button leaves it false. Tapping the view also leaves it unfocused, although the tap is received. Pressing Tab can focus the same view. struct FocusProbeView: View { @FocusState private var isFocused: Bool var body: some View { VStack { Text("Target") .focusable(interactions: .edit) .focused($isFocused) .onTapGesture { print("Target tapped") } Text("isFocused = \(isFocused)") Button("Focus target") { isFocused = true } } .defaultFocus($isFocused, true) } }Steps to reproduce: Run this view on an iPad with a hardware keyboard connected. Tap “Focus target”, then tap “Target”. Observe that isFocused remains false. Press Tab. The target can receive focus through keyboard navigation. Disconnect the keyboard. Restart the app and tap “Focus target” again. isFocused becomes true. Reconnecting the keyboard does not remove that focus. Expected: A visible custom view marked .focusable(interactions: .edit) can receive focus through @FocusState, including when a hardware keyboard is connected. Actual: Programmatic focus fails when the keyboard is already connected. A native TextField tested with the same button and @FocusState does receive focus. Environment: iPad model: MU1V2NF/A; iPadOS version: 26.7.2; Xcode version: 27.2; hardware keyboard: Logi Folio Touch. iPad model: Device Hub iPad Pro 11-inch (M5); iPadOS version: 27.2; Xcode version: 27.2; hardware keyboard: Device Hub.
1
0
221
1d
Multiseat Subscriptions: Pricing Flexibility and Enterprise Implementation
I have questions about pricing flexibility and technical implementation. In WWDC26 Session 391, you introduced up to five volume pricing bands that allow developers to offer lower per-seat subscription prices as organizations purchase more seats. For example: 1–20 seats: $39.99/month per seat 21–40 seats: $29.99/month per seat 41+ seats: $19.99/month per seat Volume purchasing and volume discounting provide different benefits. Volume purchasing makes it easier for organizations to buy, deploy, and manage subscriptions. This is valuable independently of discounts. Consider a productivity application deployed to 10,000 employees. Unlike AI services that charge separately for tokens or usage credits, an application offering unlimited, unmetered usage receives no additional revenue beyond its subscription fees. Supporting 10,000 deployments also introduces ongoing responsibilities. Major updates, new capabilities, and performance improvements may require additional testing, deployment coordination, compatibility checks, and technical support. Enterprise customers often have greater requirements for reliability, timely updates, and deployment management. Reducing the fixed subscription price per seat does not reduce these responsibilities or account for the additional value delivered across an organization. My questions for the StoreKit team: Business pricing: Can developers create a separate business subscription with a higher base price than their consumer offering, such as $39.99/month for individuals and $59.99/month per business seat, with independent volume pricing bands? Business-only distribution: Can this subscription be offered exclusively through Apple Business while maintaining the existing consumer subscription? Business features in the same app: Can StoreKit 2 identify whether a user has an individual subscription or an organization-assigned seat, allowing developers to unlock additional business capabilities within the same app binary? Onboarding and deployment: What is the recommended approach for adapting onboarding, subscription unlocking, and access management for organization-assigned users? Are there specific considerations for MDM deployment and managed app configurations? Implementation resources: Are there technical documentation or sample projects covering multiseat purchases, entitlement verification, seat reassignment, subscription changes, and ongoing management after release? The primary opportunity is simplifying organizational purchasing and deployment, while allowing developers to deliver additional business value and price subscriptions according to the ongoing requirements of supporting organizations at scale—not simply discounting additional seats. I’d appreciate clarification on the recommended pricing configuration and StoreKit 2 implementation. Thank you. REF: October 22 Announcement — Offer your subscriptions to businesses and schools
1
0
154
1d
Inversed swipe gesture in VStack/LazyVStack vs List
I'm using a row swipe to delete gesture in a LazyVStack just the same way I would do in a List and I have to inverse the gesture (from left to right) to allow the Delete button appearing whereas in a List, the left to right swipe gesture works as expected. The following code reveals that unexpected/anti natural behavior. iOS works as expected for the same code. import SwiftUI import Playgrounds struct ContentView: View { var body: some View { VStack { // anti-natural and inconsistent gesture // LazyVStack { // anti-natural and inconsistent gesture // List { // natural gesture HStack { Text("Swipe Test") Spacer() } .padding(10) .frame(height: 40) .background { Color.blue } .swipeActions(edge: .trailing, allowsFullSwipe: false) { Button("Delete", role: .destructive) {} } } } }Setup: Macbook Pro M1 Max / macOS 27.2.1 / Xcode 27.2
0
0
31
1d
Supported way to hide the system time in a full-screen watchOS clock app?
I'm building a standalone watchOS app (SwiftUI, watch-only) whose main screen is its own full-screen clock. The system time in the top-right corner duplicates our clock, so we'd like to hide it while this view is visible. I'd like to know which API is supported for this in an App Store app. What I tried (watchOS 27.2 SDK, Xcode 27.2): .persistentSystemOverlays(.hidden) on the root view and on the scene. The system time stays visible. In a variant with a NavigationStack and a hidden navigation bar, the time was briefly absent after launch, but it came back within about 20 seconds. .statusBarHidden(_:) and .toolbarVisibility(.hidden, for: .statusBar) are marked unavailable on watchOS in the SDK. View._statusBarHidden(_:) hides the system time reliably. In the watchOS SwiftUI interface it is public, available on watchOS since 6.0, and has no @_spi. It inlines to _statusBar(hidden:). However, it's underscored and I can't find documentation for it. Minimal example: struct ClockView: View { var body: some View { MyFullScreenClock() .persistentSystemOverlays(.hidden) // documented, but time remains visible ._statusBarHidden(true) // hides the time, but undocumented } }I've noticed this modifier in shipping open-source watchOS code, for example Home Assistant's watch app (Sources/WatchApp/Home/WatchHomeView.swift). That doesn't tell me whether Apple supports it, though. Questions: Is _statusBarHidden(_:) / _statusBar(hidden:) a supported API for a distributed watchOS app? If not, is there a documented way for a full-screen clock app to hide the system time, or is the system time intentionally always shown in third-party apps? I can share a small sample project that toggles between the documented overlay preference and the underscored modifier. Thanks!
2
0
75
1d
Supported way for a watchOS clock app to stay frontmost after the screen dims?
I'm building a standalone watchOS app (SwiftUI, watch-only) whose main screen is its own full-screen clock. Users who choose this clock want it to remain the screen they see on wrist raise, instead of returning to the system watch face after the inactivity timeout. I'd like to know whether watchOS supports this for an App Store app, and which API to use. What I've looked at (watchOS 27.2 SDK, Xcode 27.2): Always On + Return to Clock. The app supports the Always On state. This works up to the Return to Clock interval the user chooses (at most one hour, per "Taking advantage of frontmost app state"). After that, the system face returns. WKApplication.isFrontmostTimeoutExtended. The documentation says it has had no effect since watchOS 7. In a test, reading it back gave false, and the app went to the background after about 2 minutes. WKExtendedRuntimeSession. The documentation asks developers to pick a session type based on the app's actual purpose (self care, mindfulness, physical therapy, smart alarm). None of these fits a clock, so I'm not using one to gain runtime. App Intents supportedModes / LongRunningIntent. These bring the app to the foreground when an intent runs, or run long background work. I couldn't find a way to use them to return automatically after the timeout. openSystemURL with the app's own URL scheme from a background callback. This didn't reopen the app. Other clock apps on the App Store offer a "keep active" style option, so I'm wondering whether a supported mechanism exists that I've missed. Questions: Is there a supported API or capability that lets a user-selected clock app stay frontmost, or come back automatically, after the inactivity timeout? Normal exits must still work: the Digital Crown, other apps, notifications, locking and Sleep Focus. If this isn't supported, is the limit intentional? Is per-app Return to Clock plus Always On the intended maximum? I can share a minimal sample (FrontmostClockProbe) that uses only public APIs and logs scene phase and luminance state. Thanks!
2
0
70
2d
Keeping the display awake during hands-free auto-scroll in a watchOS reading app
I develop Folito, a free watchOS app for reading EPUB books on Apple Watch. We added an auto-scroll mode: the text scrolls continuously at a speed the user sets with the Digital Crown, so they can read hands-free with their wrist raised. The display dims after the wake timeout because auto-scroll isn't user interaction, so the text becomes hard to read after 15–70 seconds while the user is still reading. What we've considered Pausing on isLuminanceReduced and resuming on tap. This works, but it needs a touch every minute. Continuing in Always On (luminance reduced) with ~1 Hz line-by-line updates. This is our current plan, but the text is dimmed and SE models have no Always On. WKExtendedRuntimeSession. None of the session types (self care, mindfulness, physical therapy, smart alarm, workout) describes reading, and we don't want to misuse one. HKWorkoutSession. Not appropriate, because it would record fake workouts. Questions Is there a supported way for a frontmost app to keep the display at normal brightness while showing continuously changing content the user is reading, without touch input? Would a WKExtendedRuntimeSession started only while auto-scroll runs (and ended as soon as it pauses or stops) be acceptable for this, and if so, which type? In Always On, what's the recommended way to keep text content advancing (for example, updating a ScrollView position via ScrollViewReader about once per second)? I found thread 720495 (iOS, isIdleTimerDisabled) and thread 122753 (Always On, 2019), but neither covers a watchOS app that needs the display awake while content advances on its own. Deployment target: watchOS 10, SwiftUI. Thanks!
1
0
260
3d
Game Center overlay places its back and Play buttons under the rounded corners (and camera) on iPhone Duo's outer display
Environment Device: iPhone Duo, closed (outer display), iOS 27.2 Xcode 27.1 (27A9275), iOS 27.1 SDK, deployment target iOS 18 SwiftUI app lifecycle (WindowGroup, generated scene manifest, generated UILaunchScreen), not letterboxed What happens On the iPhone Duo's outer display, the Game Center screens that GKAccessPoint.trigger(...) opens put their top controls (the round back button at the top left, the "Play" button at the top right) right up in the display's rounded top corners, where the corner partly clips them. The same screens look correct on other iPhones. The outer display's status sits in a column at the right, so a full-screen window there gets a top safe area inset of 0. On other iPhones the top inset (status bar or Dynamic Island) keeps these buttons clear of the corners. The overlay appears to rely on that inset and has no margin of its own for the display's corner radius. Our own app content on the same display handles this: when the top safe area is 0 we add a fixed top margin. The Game Center overlay has no API for us to do the same, at least none that we can find. Steps to reproduce Sign in to Game Center on an iPhone Duo and keep it closed (outer display). In any app, call GKAccessPoint.shared.trigger(leaderboardID: "<id>", playerScope: .global, timeScope: .allTime, handler: {}) Look at the top corners of the Game Center screen, on the leaderboards list and on a single leaderboard. Expected: the back and Play buttons sit clear of the rounded corners, as on other iPhones. Actual: they sit under the corners (screenshot, though it doesn't show the camera cutout) What we tried (none changed the layout at all) Binding the access point to our window before every trigger: let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } .first { $0.activationState == .foregroundActive } if let window = scene?.keyWindow { GKAccessPoint.shared.parentWindow = window } GKAccessPoint.shared.trigger(leaderboardID: id, playerScope: .global, timeScope: .allTime, handler: {}) Hosting GKGameCenterViewController (deprecated in iOS 26, used only for this test) as a child of our own full-screen view controller, with a top safe area margin: final class GameCenterHolder: UIViewController, GKGameCenterControllerDelegate { let screen: GKGameCenterViewController // GKGameCenterViewController(leaderboardID:playerScope:timeScope:) // init sets modalPresentationStyle = .fullScreen override func viewDidLoad() { super.viewDidLoad() screen.gameCenterDelegate = self addChild(screen); view.addSubview(screen.view); screen.didMove(toParent: self) } override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() screen.additionalSafeAreaInsets.top = view.safeAreaInsets.top < 1 ? 20 : 0 } nonisolated func gameCenterViewControllerDidFinish(_ vc: GKGameCenterViewController) { MainActor.assumeIsolated { dismiss(animated: true) } } }The screen opened and worked, but its layout was identical. The same holder, giving the child a smaller frame instead (starting 20 pt lower): override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let top: CGFloat = view.safeAreaInsets.top < 1 ? 20 : 0 screen.view.frame = view.bounds.inset(by: UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)) }Still identical, so the screen seems to be drawn by the system outside the app's view hierarchy, out of the app's reach. We also checked the usual causes: the app is built with the iOS 27.1 SDK, uses the scene lifecycle and a generated launch screen, doesn't use UIScreen.main for layout, and fills the outer display edge to edge (not letterboxed).
0
0
108
3d
@FocusedValue from .focusedSceneValue from the Scene Commands
Hi, In iPadOS can we use a .focusedSceneValue, defined from a command/Button inside a Scene, from inside the .command modifier attached to the scene? Like this: @main struct test_focusedSceneValueApp: App {     var body: some Scene {         WindowGroup {             ContentView()         }         .commands {             NavigationCommands()         }     } } struct NavigationCommands: Commands {     @FocusedValue(\.filterAction) var filterAction     var body: some Commands {         CommandMenu("Navigate") {             Button("Test focusedSceneValue") {                 filterAction?()             }             .keyboardShortcut("5")         }     } } struct ContentView: View {     @FocusState var isFiltering: Bool     @State private var focusField: String = "teste field teste"     var body: some View {         TextField("teste focus", text: $focusField)             .focused($isFiltering)             .focusedSceneValue(\.filterAction) {                 print("test successful")                 isFiltering = true             }     } This code is almost the same from the sample code from the documentation, however I can only retrieved nil values from the @FocusedValue and not the defined value. Thanks.
5
0
2.2k
5d
Content View Not Working
Newbie here. I just downloaded the latest version Xcode, because I started a class in iOS coding. Unfortunately I write my first "app" (yeah it's "Hello, World"!) and the ContentView just spins and soins then generates an error meassage that goes back to Apple. By the way the iPhone simulater loads but shows nothing. I spoke with two Apple support people to no avail. Can anyone here help? P.S. The error meassages are always Xcode stopped unexpectedly.
0
0
85
6d
Button or onTapGesture grows its hit region by a fixed amount past the view’s bounds.
SwiftUI Button hit area extends ~16pt beyond its visual frame — expected OS behavior? Hi everyone, I’m working on a custom SwiftUI segmented control and noticed some unexpected hit-testing behavior with Button. I have a button structured roughly like this: Button { selectItem(at: index) } label: { ZStack { if selectedIndex == index { selectedBackground } SegmentCellView( tab: tab, isSelected: selectedIndex == index ) } .frame(maxWidth: .infinity) .contentShape(Rectangle()) } .accessibilityLabel(Text(tab.labelText)) The visual frame of the button has a certain height, but when testing on a real device, I can tap approximately 16pt outside the button's visible frame and the button still receives the tap. This seems to happen even though I explicitly use: .contentShape(Rectangle()) to define the tappable shape. My questions are: Is this ~16pt expansion of the interactive area expected SwiftUI/OS behavior? Is this related to Apple's minimum hit-target/accessibility guidelines being automatically applied to controls such as Button? If so, is there an official API/documentation describing this behavior? Is there a recommended way to make the Button's hit-testing area exactly match the bounds defined by .contentShape(Rectangle()), if that is actually possible? I'm particularly interested in understanding whether this is intentional system behavior or something caused by the ButtonStyle / layout hierarchy. Thanks!
2
1
146
6d
iPhone Duo: Keep app on inner display while hinge is open (like Clock)?
Hi! I'm building a night-light app for iPhone Duo. When the device is partly open in tent mode, the lamp starts on the inner display. As soon as I set the phone down on a table, the system moves my window to the outer display, even though the hinge stays open. Apple's Clock app stays on the inner display in the same pose, so it seems possible at the system level. Steps Open iPhone Duo to ~80° (tent). Launch the app on the inner display. Set the device down on a table. Observed (logged from the app) UIHinge.status stays .partiallyOpen (~80°), not .closed. UIDevice.orientation goes portraitUpsideDown → faceDown → landscapeRight. UIScreen.didDisconnectNotification fires and UIScreen.screens drops the inner screen. The window moves to the outer screen (466×678). What I've tried Restricting UISupportedInterfaceOrientations to portrait only Turning on Rotation Lock Reading UIHingeInteraction (read-only, no effect on display routing) Looking at UISceneAccessory.cameraCapture, which only applies with an active capture session and a fully open device Question Is there a supported way for a scene to prefer or stay on the inner display while the hinge isn't closed? If not, I'll file a Feedback Assistant request. iPhone Duo · iOS 27.2 · Xcode 27.2
1
0
67
1w
Tab grayed out, but not disabled
Bug report: FB25495244 This bug also appeared with Xcode 27; it worked previously. scenario: A TabView with, for example, 4 tabs. Data in ContentView is loaded via @Query. In ContentBindingView, the same thing is done, but using a parameter instead of SwiftData. ContentView: If no data is available, the system automatically switches to tab 4 at the start; while you can click on other tabs, they are disabled, and the system will not switch to them. ContentBindingView: When tabDisabled is set to "true", the system automatically switches to Tab 4 upon startup; while it is possible to click on other tabs, they are disabled, and the system will not switch to them. So far, so good. The first three tabs are only active if at least one data record exists or tabDisabled is "false". Tab 4 is always active and is used for data entry. When data is entered in Tab 4, tab 1 to 3 should become active. However, it appears as though tabs 1 through 3 remain disabled—the icons appear grayed out. That is actually not the case; you can click on the tabs, and as soon as you move away from a tab, its icon is displayed correctly. This issue did not exist in Xcode 26. In Xcode 26, all symbols were displayed correctly from the start, once data had been saved. What I noticed on the iPhone Duo: If you open the program on an iPhone Duo while it is closed, enter some data, then move the app to the background, open the iPhone Duo, and bring the application back to the foreground, tabs 1 through 3 will be active. The entire view is being updated, which is why tabs 1 through 3 are now active—though they should have been active already. A side note: The same issue described in the forum post "A layout bug when using Tab View in SwiftUI (FB25490881)" also occurs in this program. The entire view has shifted upward. The text field is no longer visible—only the Add button remains. In the other views, you can only see half of the text. import SwiftUI struct ContentBindingView: View { @State private var tabDisabled: Bool = true @State private var selection: TabSelection = .tab1 private var isTabDisabled: Bool { print("ContentView.isTabDisabled: \(tabDisabled)") return tabDisabled } var body: some View { TabView(selection: $selection) { Tab("Tab 1", systemImage: "waveform.badge.magnifyingglass", value: .tab1) { Text("tab 1") } .disabled(isTabDisabled) Tab("Tab 2", systemImage: "heart", value: .tab2) { Text("tab 2") } .disabled(tabDisabled) Tab("Tab 3", systemImage: "target", value: .tab3) { Text("tab 3") } .disabled(tabDisabled) Tab("Tab 4", systemImage: "gear", value: .tab4) { AddFriendBindingView(tabDisabled: $tabDisabled) } } .onAppear { print("ContentView onAppear disabled: \(tabDisabled)") if tabDisabled { selection = .tab4 } } .onChange(of: selection) { print("ContentView onChange disabled: \(tabDisabled)") } } }struct AddFriendBindingView: View { @Environment(\.dismiss) private var disdmiss @Binding var tabDisabled: Bool @State private var name: String = "" var body: some View { VStack { TextField("Name", text: $name) Button { addFriend() } label: { Text("Add") } .buttonStyle(.borderedProminent) } .padding() .onAppear { print("AddFriendView onAppear disabled: \(tabDisabled)") } } private func addFriend() { tabDisabled = false name = "" disdmiss() } }Christian
2
0
294
1w
App issues with battery icons after upgrading to iOS 27.2.1
My app displays a battery icon using the SF Symbols library. After upgrading my iPhone from iOS 27 to 27.2.1, the battery icon is not displayed correctly anymore as the foreground colours are being applied differently. It seems that the primary and secondary foreground styles are swapped. Also it seems that the 100% icon now only applies the primary style. I created a small example that shows my issue. Here is a comparison from an iPhone Duo simulator running iOS 27.1, and my iPhone running iOS 27.3: As you can see, the colours are now swapped for 25%, 59%, and 75%, and the full icon only has only one colour with no outline. So my question is: Is this expected/intentional, and if so, am I expected to just work around it? --- ### Example code: ```swift struct ContentView: View { var body: some View { VStack { Image(systemName: "battery.0percent") .foregroundStyle(.green, .red) Image(systemName: "battery.25percent") .foregroundStyle(.green, .red) Image(systemName: "battery.50percent") .foregroundStyle(.green, .red) Image(systemName: "battery.75percent") .foregroundStyle(.green, .red) Image(systemName: "battery.100percent") .foregroundStyle(.green, .red) } } } #Preview { ContentView() } ```
Replies
0
Boosts
0
Views
145
Activity
8h
SwiftUI TabView with a .prominent tab exhibits unexpected rendering behavior during iPhone Duo display transitions
Hi Apple Support Team, I would like to report an iPhone Duo-specific regression that appears in iOS 27.2.1. The same application behaves correctly on iOS 27.1, and I have been able to reproduce the issue consistently using a minimal sample application. When running the application on iPhone Duo, transitioning from the outer display to the inner display while the device is opened in landscape orientation results in unexpected UI rendering. Specifically, a large arc-shaped visual element associated with a tab configured with the .prominent role appears on screen after the transition. In addition to the rendering issue, we have observed unexpected UI presentation behavior during these display transitions when a tab is assigned the .prominent role. The issue appears to be tied to the .prominent tab role. When all tabs use the default role, the application behaves as expected and neither the rendering issue nor the unexpected UI behavior is observed. A sample application reproducing the issue is attached. Steps to Reproduce Launch the attached sample application on iPhone Duo running iOS 27.2.1. Ensure that one of the tabs is configured with the .prominent role. Start on the outer display. Open the device and transition to the inner display in landscape orientation. Observe the UI during and after the transition. Expected Result TabView should transition cleanly between the outer and inner displays without rendering artifacts or unexpected UI behavior. Actual Result A large arc-shaped visual artifact appears on screen. Unexpected view presentation behavior may occur during the display transition. Multiple animation- and transform-related warnings are logged. // Attached run time logs. Additional Notes Reproducible in both our production application and the attached sample application. The issue appears to be tied to SwiftUI TabView when a tab is assigned the .prominent role. The issue was not observed on iOS 27.1. The issue occurs during transitions between the outer and inner displays on iPhone Duo. Removing the .prominent role eliminates the issue. Could you please let us know whether this is a known issue with SwiftUI TabView and .prominent tabs during iPhone Duo display transitions on iOS 27.2.1? If there is an existing Feedback report, Apple Developer Forums discussion, internal tracking issue, or recommended workaround, we would greatly appreciate any guidance. Screenshots and a sample project are attached. Thank you for your time and assistance. Please let me know if any additional diagnostics, sysdiagnose captures, logs, or sample projects would be helpful. Best regards, Manish
Replies
1
Boosts
0
Views
169
Activity
9h
Regression: AxisValueLabel multiLabelAlignment parameter ignored in iOS 27
Hello Apple SwiftUI / Swift Charts Engineering Team, I am writing to report a layout regression regarding Swift Charts in iOS 27. The multiLabelAlignment property on AxisValueLabel has stopped working as expected, whereas it functions perfectly in iOS 26. Bug Description: When configuring custom string values within AxisMarks using AxisValueLabel with multiLabelAlignment: .trailing, the alignment configuration is completely ignored on iOS 27. Labels fail to align text properly to the trailing edge, causing rendering layout issues for multi-line or custom text labels on the Y-axis. This exact same implementation compiles and aligns correctly on iOS 26. Code Snippet to Reproduce: swift struct YAxisAlignmentBugView: View { // data points to render the chart frame let data = [(date: Date(), revenue: 3000.0), (date: Date().addingTimeInterval(10000), revenue: 4000.0)] var body: some View { Chart(data, id: .date) { item in LineMark(x: .value("Date", item.date), y: .value("Revenue", item.revenue)) } .frame(height: 300) .padding() .chartYAxis { AxisMarks(preset: .aligned, position: .trailing, values: [12.0, 600.0, 3000.0, 6000.0]) { value in if let revenue = value.as(Double.self) { // BUG: multiLabelAlignment: .trailing is completely ignored on iOS 27 AxisValueLabel("y-(Int(revenue))", anchor: .leading, multiLabelAlignment: .trailing) } } } } } Steps to Reproduce: Render a Swift Chart containing a .chartYAxis configuration with position: .trailing. Pass a string directly using AxisValueLabel(customText, anchor: .leading, multiLabelAlignment: .trailing). Run the application on an iOS 26 simulator (text aligns properly to the trailing edge). Run the identical application code on an iOS 27 simulator. Expected Behavior: The text inside the AxisValueLabel should honor the multiLabelAlignment: .trailing parameter and align the text strings flush right. Actual Behavior: The multiLabelAlignment layout modifier is ignored on iOS 27, resulting in unexpected default left-alignment of the text strings. Attachments: I have attached screenshots from the Xcode Simulator demonstrating the regression: Please let me know if you need any further diagnostic details. Best regards, Soumyajit Das
Replies
3
Boosts
0
Views
306
Activity
11h
Regression: AxisValueLabel anchor parameter ignores .topLeading on iOS 27
Hello Apple SwiftUI / Swift Charts Engineering Team, I am writing to report a layout regression regarding Swift Charts in iOS 27. The anchor property on AxisValueLabel has stopped honoring the .topLeading layout coordinate, whereas it functions perfectly in iOS 26. Bug Description: To prevent the first label on a bottom X-axis from clipping past the left screen edge, a .topLeading anchor is applied. In iOS 27, this specific anchor alignment is completely ignored. The chart falls back to a standard top-center alignment, causing the initial boundary label to clip off-screen. Core Code Snippet to Reproduce: struct XAxisAnchorBugView: View { let dates = [ Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 1))!, Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 2))! ] var body: some View { Chart(dates, id: .self) { date in LineMark(x: .value("Date", date), y: .value("Value", 100)) } .frame(height: 300) .padding() .chartXAxis { AxisMarks(preset: .aligned, position: .bottom, values: .stride(by: .day, count: 1)) { value in AxisTick() let currentAnchor: UnitPoint = { guard let currentDate = value.as(Date.self) else { return .top } // BUG: .topLeading layout anchor parameter is completely ignored on iOS 27 return (currentDate == dates.first) ? .topLeading : .top }() AxisValueLabel(format: .dateTime.month(.abbreviated).day(), anchor: currentAnchor) } } } } Steps to Reproduce: Render an X-axis with a .bottom position. Assign anchor: .topLeading strictly to the first axis element's label. Run on an iOS 26 simulator (the first label anchors its top-left corner correctly, preventing edge clipping). Run on an iOS 27 simulator (the .topLeading anchor is ignored, reverting to standard top-center alignment). Expected Behavior: AxisValueLabel should position its layout bounding box using the .topLeading anchor point when specified. Actual Behavior: The layout engine ignores the .topLeading parameter on iOS 27, causing the boundary text to shift left and clip. Attachments: I have attached Xcode Simulator screenshots demonstrating this regression: Best regards, Soumyajit Das
Replies
3
Boosts
0
Views
329
Activity
12h
iPhone Duo Unfolded Safe Areas
Hi, my app is currently built on Xcode 27.1 I am working on upgrading to Xcode 27.2 We have a regression issue whereby, the top safeArea is 82 despite the vertical bar being opted in and active. This only happens on unfolded landscape. Our right safeArea is 0 for the window and is 84 for the view safeArea. Both window and view safeAreas have the top safe area of 82 though. We would like to know what could be the cause behind the top safeArea being activated. Note: this is not an issue for iOS 27.1
Replies
2
Boosts
0
Views
187
Activity
1d
SwiftUI Architecture Guide
Application Types Applications are divided into Document-based and Library-based. A document-based application stores user data in individual, standalone files. Users manually name and organize those files in a local system or synced cloud storage such as iCloud. The software typically opens multiple windows for different projects. This framing is for standalone, complex files that need to be shared, exported, or handled independently. A library-based application manages data in one unified, central repository, locally or through remote cloud databases. Spotify, Netflix, and Notion are the examples shown. The file system is hidden; updates are saved automatically in real time; and a single window supports browsing, search, and access to the synchronized data collection from any device. Model Types Four model types: Data, Domain, Application, and Presentation. Apple Platforms In Apple MVC (AppKit / UIKit), the model branches to Data, Domain, and Presentation. In SwiftUI, Model branches to Data and Domain. Project Structure SwiftUI App Folders Swift Package Folders App Modularization Not every module in a large application needs to be extracted into a separate framework or Swift Package. Logical modularization can also be achieved through a well-organized folder structure within the main project. Introduce separate packages or frameworks only when there is a clear benefit, such as independent reuse, distribution, build isolation or ownership. Avoid unnecessary project and dependency management overhead. State Management & Data Flow Source of truth is “a key concept in SwiftUI”: a single place to store a piece of data, with everywhere else reading the same piece of data. Environment is SwiftUI’s native dependency-injection mechanism. It allows shared dependencies, domain models, and services to be injected at the appropriate view-hierarchy level and accessed where needed without explicit parameter passing or unnecessary coupling. It is described as a tool for managing dependencies and sharing state across the view hierarchy. Domain Model Ownership Domain Models should be owned by the highest relevant SwiftUI view in the hierarchy that defines their context and lifecycle. NavigationStack owns the Domain Models for its navigation context and makes them available to descendant views through @Environment. When a NavigationStack is embedded in a TabView or NavigationSplitView, ownership moves up to the TabView or NavigationSplitView so the models can be shared across tabs or split views. The stated result is clear ownership scope, sharing where needed, and isolation between independent navigation contexts. Previews & UI Testing Environment injection makes SwiftUI Previews and UI Tests easier to configure by allowing real Domain Models to be replaced with mock or dummy instances. Views can be tested independently with controlled data and predictable states, without requiring real services, network requests, or application setup. Domain and Data Model Examples For a library-based app with remote data. Additional Domain Model Examples E-commerce Catalog, ShoppingCart, OrderHistory, Wishlist Banking MyAccounts, MyCards, MyTransactions, MyInvestments Social Network Feed, Conversations, Notifications, Friends Healthcare MyAppointments, MedicalHistory, Prescriptions, MyHealth Education Courses, MyCourses, Assignments, MyGrades, LearningProgress Real Estate PropertyCatalog, MyProperties, Favorites, Appointments Hotel Booking Destinations, Search, MyBookings, TravelHistory Food Delivery RestaurantCatalog, ShoppingCart, MyOrders, DeliveryTracking Project Management Projects, MyTasks, TeamMembers, Notifications Insurance MyPolicies, MyClaims, Coverage, Documents Smart Home MyHomes, Devices, Automations, EnergyUsage Fitness MyPlans, MyProgress, MyGoals, WorkoutHistory Other Search, Dashboard, Favorites, Notifications, Settings, ActivityHistory, Recommendations, Subscription, DocumentLibrary ViewModel? - MVVM In SwiftUI, the View encapsulates the UI content (body), its state (properties), and its actions or tasks (functions). This is possible because SwiftUI is designed around a declarative, state-driven UI model. In Android and .NET platforms, a separate ViewModel is typically required to hold and manage the View's state. Projects that intoduce ViewModels in SwiftUI add unnecessary architectural complexity, boilerplate, and code duplication; synchronization issues; unclear state ownership; additional lifecycle management; more abstractions; harder debugging; and increased maintenance, without meaningful benefits over SwiftUI's native state management. In UIKit, introducing a separate ViewModel layer is often unnecessary, as UIViewController already serves as the presentation model, handling presentation logic and coordinating the view. Non-UI responsibilities can be delegated to dedicated ModelControllers or Managers, avoiding unnecessary layers and abstractions. Domain Models vs. ViewModels Domain Models are view-independent, while ViewModels are view-dependent. A ViewModel is tightly coupled to the structure, state, and lifecycle of a specific View. Whenever the View code changes, its ViewModel often requires corresponding coding changes, and vice versa, creating additional maintenance and synchronization overhead. Domain Models, on the other hand, represent application context and business functionality independently of the UI. This separation preserves UI independence and allows the same Domain Models to be shared across different screens and platforms, such as iPhone, iPhone Duo, iPad, and macOS, without duplicating or adapting business logic for each View. This makes Domain Models a more scalable and maintainable approach for modern SwiftUI applications, particularly those targeting multiple screen sizes and platforms.
Replies
1
Boosts
0
Views
246
Activity
1d
Accessibility Inspector Element Detection and contrast failures with SwiftUI sheets
I am investigating Accessibility Inspector/XCTest audit results in a SwiftUI app (Target Keeper), without suppressing warnings. Environment: Xcode 27.1 (27A9275), iPadOS 27.0 Simulator, macOS 27.0.1. Debug and Release builds pass. The app uses scalable text and labeled controls. Element Detection / native sheet Main-screen Element Detection passes when the sheet is closed. With a SwiftUI .sheet presented, the iPad audit reports “Potentially inaccessible text”; XCUIAccessibilityAuditIssue.element is nil. Exported Inspector HTML highlights background labels behind/outside the sheet, rather than a foreground control. The separate, data-free SwiftUI application below reproduces the modal-only warning; it links no application modules or persistence. Actual iPad Simulator VoiceOver testing using XCUIDevice.shared.voiceOverService passes forward/backward traversal of the real application's modal controls, without reaching the background labels. This is simulator evidence, not physical-device acceptance. A trial explicit modal container/.isModal trait did not clear the audit and was reverted; no warnings are filtered. Minimal independent app: import SwiftUI @main struct ModalRepro: App { @State private var showing=false private let names=["Vegetables","Protein","Fruit","Dairy","Grains","Healthy Fats"] var body:some Scene {WindowGroup { NavigationStack { VStack(spacing:24) { Button("Nutrition") {}.accessibilityLabel("Choose Page").accessibilityValue("Nutrition") LazyVGrid(columns:[GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())],spacing:40) { ForEach(names,id:\.self) { name in Button {} label: { VStack(spacing:10) { Circle().fill(.blue.opacity(0.3)).frame(width:250,height:250) Text(name).font(.system(size:17)).accessibilityHidden(true) } }.buttonStyle(.plain).accessibilityLabel(name) } } Button("Show modal") {showing=true} }.padding(24).frame(maxWidth:.infinity,maxHeight:.infinity).background(Color.black) }.preferredColorScheme(.dark) .sheet(isPresented:$showing) { NavigationStack { VStack {Text("Foreground content");Button("Close") {showing=false}} .frame(maxWidth:.infinity,maxHeight:.infinity).background(Color.black) .navigationTitle("Modal flow") }.preferredColorScheme(.dark) } }} }In an Xcode UI-test target, launch this app, run try app.performAccessibilityAudit(for: [.elementDetection]), tap “Show modal”, then run the same audit again. The first passes and the second fails. No issue handler ignores failures. Contrast / scrolling — separate unresolved finding All four iPhone combined-audit configurations (portrait/landscape, normal/maximum Dynamic Type) pass in the tested picker state. However, iPad maximum-text combined audits and a separate scrolled iPhone maximum-text landscape contrast audit still fail; we are not calling these resolved. In the scrolled iPhone case, XCTest identifies a count label whose frame is entirely above the visible results viewport. Inspector's exported HTML reports 1.37:1 using #252526 versus #000000; its marked screenshot rectangle overlaps the dark search/header area, not visible count text. Visible sampled labels instead have white or light foregrounds on opaque dark fills (e.g. #FFFFFF/#1C1C1E = 17.01:1; #98989F/#1C1C1E = 5.94:1). These are screenshot core-pixel measurements, not proof every warning is false. We compare ordinary text against 4.5:1 and interactive non-text against 3:1. iPad maximum-text warnings have not yet been matched to an exact visible color pair. Original failures and HTML exports are preserved privately. Questions Is Element Detection expected to inspect background elements behind a presented native SwiftUI sheet? Is this a known tool limitation/framework issue, or does the sample need different semantics? What is the supported way to establish modal accessibility boundaries with SwiftUI sheets, and when should .isModal be added explicitly? How should we distinguish a real contrast defect from clipping, occlusion, translucency, or sampling of an offscreen element? Which Inspector export fields/diagnostics should establish the actual sampled text/background pair? What additional evidence/manual and physical-device tests does Apple recommend before qualifying accessibility when the minimal audit reproduction fails but actual VoiceOver modal focus behaves correctly? We are not asking to waive audits or declare full accessibility from a VoiceOver pass alone. I read Apple's audit guidance and modal trait documentation: https://developer.apple.com/documentation/accessibility/performing-accessibility-audits-for-your-app https://developer.apple.com/documentation/swiftui/accessibilitytraits/ismodal https://developer.apple.com/help/app-store-connect/manage-app-accessibility/sufficient-contrast-evaluation-criteria/ Related discussion https://developer.apple.com/forums/thread/823968 recommends Feedback for a different apparent Dynamic Type false positive; it does not answer these modal/contrast questions. A Feedback draft is prepared but not submitted, so I have no Feedback ID yet. No private data, identifiers, credentials, app containers or confidential application source are included.
Replies
2
Boosts
0
Views
1.2k
Activity
1d
SwiftUI custom focusable view cannot acquire focus programmatically on iPad with a hardware keyboard connected
On iPad, a SwiftUI view using .focusable(interactions: .edit) and .focused($isFocused) cannot acquire focus when a hardware keyboard is already connected. Setting isFocused = true from a button leaves it false. Tapping the view also leaves it unfocused, although the tap is received. Pressing Tab can focus the same view. struct FocusProbeView: View { @FocusState private var isFocused: Bool var body: some View { VStack { Text("Target") .focusable(interactions: .edit) .focused($isFocused) .onTapGesture { print("Target tapped") } Text("isFocused = \(isFocused)") Button("Focus target") { isFocused = true } } .defaultFocus($isFocused, true) } }Steps to reproduce: Run this view on an iPad with a hardware keyboard connected. Tap “Focus target”, then tap “Target”. Observe that isFocused remains false. Press Tab. The target can receive focus through keyboard navigation. Disconnect the keyboard. Restart the app and tap “Focus target” again. isFocused becomes true. Reconnecting the keyboard does not remove that focus. Expected: A visible custom view marked .focusable(interactions: .edit) can receive focus through @FocusState, including when a hardware keyboard is connected. Actual: Programmatic focus fails when the keyboard is already connected. A native TextField tested with the same button and @FocusState does receive focus. Environment: iPad model: MU1V2NF/A; iPadOS version: 26.7.2; Xcode version: 27.2; hardware keyboard: Logi Folio Touch. iPad model: Device Hub iPad Pro 11-inch (M5); iPadOS version: 27.2; Xcode version: 27.2; hardware keyboard: Device Hub.
Replies
1
Boosts
0
Views
221
Activity
1d
Multiseat Subscriptions: Pricing Flexibility and Enterprise Implementation
I have questions about pricing flexibility and technical implementation. In WWDC26 Session 391, you introduced up to five volume pricing bands that allow developers to offer lower per-seat subscription prices as organizations purchase more seats. For example: 1–20 seats: $39.99/month per seat 21–40 seats: $29.99/month per seat 41+ seats: $19.99/month per seat Volume purchasing and volume discounting provide different benefits. Volume purchasing makes it easier for organizations to buy, deploy, and manage subscriptions. This is valuable independently of discounts. Consider a productivity application deployed to 10,000 employees. Unlike AI services that charge separately for tokens or usage credits, an application offering unlimited, unmetered usage receives no additional revenue beyond its subscription fees. Supporting 10,000 deployments also introduces ongoing responsibilities. Major updates, new capabilities, and performance improvements may require additional testing, deployment coordination, compatibility checks, and technical support. Enterprise customers often have greater requirements for reliability, timely updates, and deployment management. Reducing the fixed subscription price per seat does not reduce these responsibilities or account for the additional value delivered across an organization. My questions for the StoreKit team: Business pricing: Can developers create a separate business subscription with a higher base price than their consumer offering, such as $39.99/month for individuals and $59.99/month per business seat, with independent volume pricing bands? Business-only distribution: Can this subscription be offered exclusively through Apple Business while maintaining the existing consumer subscription? Business features in the same app: Can StoreKit 2 identify whether a user has an individual subscription or an organization-assigned seat, allowing developers to unlock additional business capabilities within the same app binary? Onboarding and deployment: What is the recommended approach for adapting onboarding, subscription unlocking, and access management for organization-assigned users? Are there specific considerations for MDM deployment and managed app configurations? Implementation resources: Are there technical documentation or sample projects covering multiseat purchases, entitlement verification, seat reassignment, subscription changes, and ongoing management after release? The primary opportunity is simplifying organizational purchasing and deployment, while allowing developers to deliver additional business value and price subscriptions according to the ongoing requirements of supporting organizations at scale—not simply discounting additional seats. I’d appreciate clarification on the recommended pricing configuration and StoreKit 2 implementation. Thank you. REF: October 22 Announcement — Offer your subscriptions to businesses and schools
Replies
1
Boosts
0
Views
154
Activity
1d
Inversed swipe gesture in VStack/LazyVStack vs List
I'm using a row swipe to delete gesture in a LazyVStack just the same way I would do in a List and I have to inverse the gesture (from left to right) to allow the Delete button appearing whereas in a List, the left to right swipe gesture works as expected. The following code reveals that unexpected/anti natural behavior. iOS works as expected for the same code. import SwiftUI import Playgrounds struct ContentView: View { var body: some View { VStack { // anti-natural and inconsistent gesture // LazyVStack { // anti-natural and inconsistent gesture // List { // natural gesture HStack { Text("Swipe Test") Spacer() } .padding(10) .frame(height: 40) .background { Color.blue } .swipeActions(edge: .trailing, allowsFullSwipe: false) { Button("Delete", role: .destructive) {} } } } }Setup: Macbook Pro M1 Max / macOS 27.2.1 / Xcode 27.2
Replies
0
Boosts
0
Views
31
Activity
1d
Supported way to hide the system time in a full-screen watchOS clock app?
I'm building a standalone watchOS app (SwiftUI, watch-only) whose main screen is its own full-screen clock. The system time in the top-right corner duplicates our clock, so we'd like to hide it while this view is visible. I'd like to know which API is supported for this in an App Store app. What I tried (watchOS 27.2 SDK, Xcode 27.2): .persistentSystemOverlays(.hidden) on the root view and on the scene. The system time stays visible. In a variant with a NavigationStack and a hidden navigation bar, the time was briefly absent after launch, but it came back within about 20 seconds. .statusBarHidden(_:) and .toolbarVisibility(.hidden, for: .statusBar) are marked unavailable on watchOS in the SDK. View._statusBarHidden(_:) hides the system time reliably. In the watchOS SwiftUI interface it is public, available on watchOS since 6.0, and has no @_spi. It inlines to _statusBar(hidden:). However, it's underscored and I can't find documentation for it. Minimal example: struct ClockView: View { var body: some View { MyFullScreenClock() .persistentSystemOverlays(.hidden) // documented, but time remains visible ._statusBarHidden(true) // hides the time, but undocumented } }I've noticed this modifier in shipping open-source watchOS code, for example Home Assistant's watch app (Sources/WatchApp/Home/WatchHomeView.swift). That doesn't tell me whether Apple supports it, though. Questions: Is _statusBarHidden(_:) / _statusBar(hidden:) a supported API for a distributed watchOS app? If not, is there a documented way for a full-screen clock app to hide the system time, or is the system time intentionally always shown in third-party apps? I can share a small sample project that toggles between the documented overlay preference and the underscored modifier. Thanks!
Replies
2
Boosts
0
Views
75
Activity
1d
Supported way for a watchOS clock app to stay frontmost after the screen dims?
I'm building a standalone watchOS app (SwiftUI, watch-only) whose main screen is its own full-screen clock. Users who choose this clock want it to remain the screen they see on wrist raise, instead of returning to the system watch face after the inactivity timeout. I'd like to know whether watchOS supports this for an App Store app, and which API to use. What I've looked at (watchOS 27.2 SDK, Xcode 27.2): Always On + Return to Clock. The app supports the Always On state. This works up to the Return to Clock interval the user chooses (at most one hour, per "Taking advantage of frontmost app state"). After that, the system face returns. WKApplication.isFrontmostTimeoutExtended. The documentation says it has had no effect since watchOS 7. In a test, reading it back gave false, and the app went to the background after about 2 minutes. WKExtendedRuntimeSession. The documentation asks developers to pick a session type based on the app's actual purpose (self care, mindfulness, physical therapy, smart alarm). None of these fits a clock, so I'm not using one to gain runtime. App Intents supportedModes / LongRunningIntent. These bring the app to the foreground when an intent runs, or run long background work. I couldn't find a way to use them to return automatically after the timeout. openSystemURL with the app's own URL scheme from a background callback. This didn't reopen the app. Other clock apps on the App Store offer a "keep active" style option, so I'm wondering whether a supported mechanism exists that I've missed. Questions: Is there a supported API or capability that lets a user-selected clock app stay frontmost, or come back automatically, after the inactivity timeout? Normal exits must still work: the Digital Crown, other apps, notifications, locking and Sleep Focus. If this isn't supported, is the limit intentional? Is per-app Return to Clock plus Always On the intended maximum? I can share a minimal sample (FrontmostClockProbe) that uses only public APIs and logs scene phase and luminance state. Thanks!
Replies
2
Boosts
0
Views
70
Activity
2d
Keeping the display awake during hands-free auto-scroll in a watchOS reading app
I develop Folito, a free watchOS app for reading EPUB books on Apple Watch. We added an auto-scroll mode: the text scrolls continuously at a speed the user sets with the Digital Crown, so they can read hands-free with their wrist raised. The display dims after the wake timeout because auto-scroll isn't user interaction, so the text becomes hard to read after 15–70 seconds while the user is still reading. What we've considered Pausing on isLuminanceReduced and resuming on tap. This works, but it needs a touch every minute. Continuing in Always On (luminance reduced) with ~1 Hz line-by-line updates. This is our current plan, but the text is dimmed and SE models have no Always On. WKExtendedRuntimeSession. None of the session types (self care, mindfulness, physical therapy, smart alarm, workout) describes reading, and we don't want to misuse one. HKWorkoutSession. Not appropriate, because it would record fake workouts. Questions Is there a supported way for a frontmost app to keep the display at normal brightness while showing continuously changing content the user is reading, without touch input? Would a WKExtendedRuntimeSession started only while auto-scroll runs (and ended as soon as it pauses or stops) be acceptable for this, and if so, which type? In Always On, what's the recommended way to keep text content advancing (for example, updating a ScrollView position via ScrollViewReader about once per second)? I found thread 720495 (iOS, isIdleTimerDisabled) and thread 122753 (Always On, 2019), but neither covers a watchOS app that needs the display awake while content advances on its own. Deployment target: watchOS 10, SwiftUI. Thanks!
Replies
1
Boosts
0
Views
260
Activity
3d
Game Center overlay places its back and Play buttons under the rounded corners (and camera) on iPhone Duo's outer display
Environment Device: iPhone Duo, closed (outer display), iOS 27.2 Xcode 27.1 (27A9275), iOS 27.1 SDK, deployment target iOS 18 SwiftUI app lifecycle (WindowGroup, generated scene manifest, generated UILaunchScreen), not letterboxed What happens On the iPhone Duo's outer display, the Game Center screens that GKAccessPoint.trigger(...) opens put their top controls (the round back button at the top left, the "Play" button at the top right) right up in the display's rounded top corners, where the corner partly clips them. The same screens look correct on other iPhones. The outer display's status sits in a column at the right, so a full-screen window there gets a top safe area inset of 0. On other iPhones the top inset (status bar or Dynamic Island) keeps these buttons clear of the corners. The overlay appears to rely on that inset and has no margin of its own for the display's corner radius. Our own app content on the same display handles this: when the top safe area is 0 we add a fixed top margin. The Game Center overlay has no API for us to do the same, at least none that we can find. Steps to reproduce Sign in to Game Center on an iPhone Duo and keep it closed (outer display). In any app, call GKAccessPoint.shared.trigger(leaderboardID: "<id>", playerScope: .global, timeScope: .allTime, handler: {}) Look at the top corners of the Game Center screen, on the leaderboards list and on a single leaderboard. Expected: the back and Play buttons sit clear of the rounded corners, as on other iPhones. Actual: they sit under the corners (screenshot, though it doesn't show the camera cutout) What we tried (none changed the layout at all) Binding the access point to our window before every trigger: let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } .first { $0.activationState == .foregroundActive } if let window = scene?.keyWindow { GKAccessPoint.shared.parentWindow = window } GKAccessPoint.shared.trigger(leaderboardID: id, playerScope: .global, timeScope: .allTime, handler: {}) Hosting GKGameCenterViewController (deprecated in iOS 26, used only for this test) as a child of our own full-screen view controller, with a top safe area margin: final class GameCenterHolder: UIViewController, GKGameCenterControllerDelegate { let screen: GKGameCenterViewController // GKGameCenterViewController(leaderboardID:playerScope:timeScope:) // init sets modalPresentationStyle = .fullScreen override func viewDidLoad() { super.viewDidLoad() screen.gameCenterDelegate = self addChild(screen); view.addSubview(screen.view); screen.didMove(toParent: self) } override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() screen.additionalSafeAreaInsets.top = view.safeAreaInsets.top < 1 ? 20 : 0 } nonisolated func gameCenterViewControllerDidFinish(_ vc: GKGameCenterViewController) { MainActor.assumeIsolated { dismiss(animated: true) } } }The screen opened and worked, but its layout was identical. The same holder, giving the child a smaller frame instead (starting 20 pt lower): override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let top: CGFloat = view.safeAreaInsets.top < 1 ? 20 : 0 screen.view.frame = view.bounds.inset(by: UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)) }Still identical, so the screen seems to be drawn by the system outside the app's view hierarchy, out of the app's reach. We also checked the usual causes: the app is built with the iOS 27.1 SDK, uses the scene lifecycle and a generated launch screen, doesn't use UIScreen.main for layout, and fills the outer display edge to edge (not letterboxed).
Replies
0
Boosts
0
Views
108
Activity
3d
@FocusedValue from .focusedSceneValue from the Scene Commands
Hi, In iPadOS can we use a .focusedSceneValue, defined from a command/Button inside a Scene, from inside the .command modifier attached to the scene? Like this: @main struct test_focusedSceneValueApp: App {     var body: some Scene {         WindowGroup {             ContentView()         }         .commands {             NavigationCommands()         }     } } struct NavigationCommands: Commands {     @FocusedValue(\.filterAction) var filterAction     var body: some Commands {         CommandMenu("Navigate") {             Button("Test focusedSceneValue") {                 filterAction?()             }             .keyboardShortcut("5")         }     } } struct ContentView: View {     @FocusState var isFiltering: Bool     @State private var focusField: String = "teste field teste"     var body: some View {         TextField("teste focus", text: $focusField)             .focused($isFiltering)             .focusedSceneValue(\.filterAction) {                 print("test successful")                 isFiltering = true             }     } This code is almost the same from the sample code from the documentation, however I can only retrieved nil values from the @FocusedValue and not the defined value. Thanks.
Replies
5
Boosts
0
Views
2.2k
Activity
5d
Content View Not Working
Newbie here. I just downloaded the latest version Xcode, because I started a class in iOS coding. Unfortunately I write my first "app" (yeah it's "Hello, World"!) and the ContentView just spins and soins then generates an error meassage that goes back to Apple. By the way the iPhone simulater loads but shows nothing. I spoke with two Apple support people to no avail. Can anyone here help? P.S. The error meassages are always Xcode stopped unexpectedly.
Replies
0
Boosts
0
Views
85
Activity
6d
Button or onTapGesture grows its hit region by a fixed amount past the view’s bounds.
SwiftUI Button hit area extends ~16pt beyond its visual frame — expected OS behavior? Hi everyone, I’m working on a custom SwiftUI segmented control and noticed some unexpected hit-testing behavior with Button. I have a button structured roughly like this: Button { selectItem(at: index) } label: { ZStack { if selectedIndex == index { selectedBackground } SegmentCellView( tab: tab, isSelected: selectedIndex == index ) } .frame(maxWidth: .infinity) .contentShape(Rectangle()) } .accessibilityLabel(Text(tab.labelText)) The visual frame of the button has a certain height, but when testing on a real device, I can tap approximately 16pt outside the button's visible frame and the button still receives the tap. This seems to happen even though I explicitly use: .contentShape(Rectangle()) to define the tappable shape. My questions are: Is this ~16pt expansion of the interactive area expected SwiftUI/OS behavior? Is this related to Apple's minimum hit-target/accessibility guidelines being automatically applied to controls such as Button? If so, is there an official API/documentation describing this behavior? Is there a recommended way to make the Button's hit-testing area exactly match the bounds defined by .contentShape(Rectangle()), if that is actually possible? I'm particularly interested in understanding whether this is intentional system behavior or something caused by the ButtonStyle / layout hierarchy. Thanks!
Replies
2
Boosts
1
Views
146
Activity
6d
iPhone Duo: Keep app on inner display while hinge is open (like Clock)?
Hi! I'm building a night-light app for iPhone Duo. When the device is partly open in tent mode, the lamp starts on the inner display. As soon as I set the phone down on a table, the system moves my window to the outer display, even though the hinge stays open. Apple's Clock app stays on the inner display in the same pose, so it seems possible at the system level. Steps Open iPhone Duo to ~80° (tent). Launch the app on the inner display. Set the device down on a table. Observed (logged from the app) UIHinge.status stays .partiallyOpen (~80°), not .closed. UIDevice.orientation goes portraitUpsideDown → faceDown → landscapeRight. UIScreen.didDisconnectNotification fires and UIScreen.screens drops the inner screen. The window moves to the outer screen (466×678). What I've tried Restricting UISupportedInterfaceOrientations to portrait only Turning on Rotation Lock Reading UIHingeInteraction (read-only, no effect on display routing) Looking at UISceneAccessory.cameraCapture, which only applies with an active capture session and a fully open device Question Is there a supported way for a scene to prefer or stay on the inner display while the hinge isn't closed? If not, I'll file a Feedback Assistant request. iPhone Duo · iOS 27.2 · Xcode 27.2
Replies
1
Boosts
0
Views
67
Activity
1w
Tab grayed out, but not disabled
Bug report: FB25495244 This bug also appeared with Xcode 27; it worked previously. scenario: A TabView with, for example, 4 tabs. Data in ContentView is loaded via @Query. In ContentBindingView, the same thing is done, but using a parameter instead of SwiftData. ContentView: If no data is available, the system automatically switches to tab 4 at the start; while you can click on other tabs, they are disabled, and the system will not switch to them. ContentBindingView: When tabDisabled is set to "true", the system automatically switches to Tab 4 upon startup; while it is possible to click on other tabs, they are disabled, and the system will not switch to them. So far, so good. The first three tabs are only active if at least one data record exists or tabDisabled is "false". Tab 4 is always active and is used for data entry. When data is entered in Tab 4, tab 1 to 3 should become active. However, it appears as though tabs 1 through 3 remain disabled—the icons appear grayed out. That is actually not the case; you can click on the tabs, and as soon as you move away from a tab, its icon is displayed correctly. This issue did not exist in Xcode 26. In Xcode 26, all symbols were displayed correctly from the start, once data had been saved. What I noticed on the iPhone Duo: If you open the program on an iPhone Duo while it is closed, enter some data, then move the app to the background, open the iPhone Duo, and bring the application back to the foreground, tabs 1 through 3 will be active. The entire view is being updated, which is why tabs 1 through 3 are now active—though they should have been active already. A side note: The same issue described in the forum post "A layout bug when using Tab View in SwiftUI (FB25490881)" also occurs in this program. The entire view has shifted upward. The text field is no longer visible—only the Add button remains. In the other views, you can only see half of the text. import SwiftUI struct ContentBindingView: View { @State private var tabDisabled: Bool = true @State private var selection: TabSelection = .tab1 private var isTabDisabled: Bool { print("ContentView.isTabDisabled: \(tabDisabled)") return tabDisabled } var body: some View { TabView(selection: $selection) { Tab("Tab 1", systemImage: "waveform.badge.magnifyingglass", value: .tab1) { Text("tab 1") } .disabled(isTabDisabled) Tab("Tab 2", systemImage: "heart", value: .tab2) { Text("tab 2") } .disabled(tabDisabled) Tab("Tab 3", systemImage: "target", value: .tab3) { Text("tab 3") } .disabled(tabDisabled) Tab("Tab 4", systemImage: "gear", value: .tab4) { AddFriendBindingView(tabDisabled: $tabDisabled) } } .onAppear { print("ContentView onAppear disabled: \(tabDisabled)") if tabDisabled { selection = .tab4 } } .onChange(of: selection) { print("ContentView onChange disabled: \(tabDisabled)") } } }struct AddFriendBindingView: View { @Environment(\.dismiss) private var disdmiss @Binding var tabDisabled: Bool @State private var name: String = "" var body: some View { VStack { TextField("Name", text: $name) Button { addFriend() } label: { Text("Add") } .buttonStyle(.borderedProminent) } .padding() .onAppear { print("AddFriendView onAppear disabled: \(tabDisabled)") } } private func addFriend() { tabDisabled = false name = "" disdmiss() } }Christian
Replies
2
Boosts
0
Views
294
Activity
1w