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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Horizontal window/map on visionOS
Hi, would anyone be so kind and try to guide me, which technologies, Kits, APIs, approaches etc. are useful for creating a horizontal window with map (preferrably MapKit) on visionOS using SwiftUI? I was hoping to achieve scenario: User can walk around and interact with horizontal map window and also interact with (3D) pins on the map. Similar thing was done by SAP in their "SAP Analytics Cloud" app (second image from top). Since I am complete beginner in this area, I was looking for a clean, simple solution. I need to know, if AR/RealityKit is necessary or is this achievable only using native SwiftUI? I tried using just Map() with .rotation3DEffect() which actually makes the map horizontal, but gestures on the map are out of sync and I really dont know, if this approach is valid or complete rubbish. Any feedback appreciated.
0
0
54
15h
Most idiotic problem with assign value to value?
Why assigning function.formula = formula does not change function.formula to formula in one go? It's always late one change behind. struct CustomFunction has defined .formula as @MainActor. I feel stupid. There is a part of code: struct CustomFormulaView: View { @Binding var function: CustomFunction @State var testFormula: String = "" @EnvironmentObject var manager: Manager .... .onChange(of: testFormula) { debugPrint("change of test formula: \(testFormula)") switch function.checkFormula(testFormula, on: manager.finalSize) { case .success(let formula): debugPrint("before Change: \(function.formula)") function.formula = formula // Nothing happens debugPrint("Test formula changed: \(testFormula)") debugPrint("set to success: \(formula)") debugPrint("what inside function? \(function.formula)") Task { //Generate Image testImage = await function.image( size: testImageSize), simulate: manager.finalSize) debugPrint("test image updated for: \(function.formula)") } .... and it produces this output when changed from 0.5 to 1.0 Debug: change of test formula: 1.0 Debug: before Change: 0.5 Debug: Test formula changed: 1.0 Debug: set to success: 1.0 Debug: what inside function? 0.5 Debug: test image updated for: 0.5 0.5 is an old value, function.formula should be 1.0 WT??
3
0
101
1d
In SwiftUI in iOS 18.1, `SectionedFetchRequest` is not refreshed when changes are done to the fetched entity's attributes.
Hi, This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17. I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this: struct ManageBooksView: View { @SectionedFetchRequest<Int16, MyBooks>( sectionIdentifier: \.groupType, sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)] ) private var books: SectionedFetchResults<Int16, MyBooks> var body: some View { NavigationStack { List { ForEach(books) { section in Section(header: Text(section.id)) { ForEach(section) { book in NavigationLink { EditView(book: book) } label: { Text(book.name) } } } } } .listStyle(.insetGrouped) } } } struct EditView: View { private var book: MyBooks init(book: MyBooks) { print("Init hit") self.book = book } } Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again. Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults. I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors. Any suggestions will be helpful, thank you.
1
0
79
4h
No screenshot files in XCResult files using Xcode 16.1
Hello, I am using Xcode 16.1 (16B40) on MacOS Sequoia 15.1.0 using a Macbook pro M1 Max I am developing an app for iOS 17 and 18 using SwiftUI I created UITests to take the screenshots for the appStore on the simulator The tests run well and all of them are succeded The problem appears when I try to get the screenshot files from the xcresult files after the test. There is not any screenshot inside it. I found a data folder and a Info.plist file. In the data folder there are a lot of files with this pattern data.03zD4C6IGFFthK14NwA8mNvcwFHT16g6Tl40Tl1YmBC1bNh6d0YIcnWKyUaQPDXoa8fYo6C3Xcv8xvMtE3_NEXA== and other files with this pattern refs.03zD4C6IGFFthK14NwA8mNvcwFHT16g6Tl40Tl1YmBC1bNh6d0YIcnWKyUaQPDXoa8fYo6C3Xcv8xvMtE3_NEXA== Ok, I tryed to use fastlane to automatize the screenshots but the problem is still present. The xcresult files have not any png file. I had no problems doing this action (getting screenshots from a xcresult file) in previous versions of MacOS and Xcode in my current machine. I just updated my machine to MacOS Sequoia 15.1.1 and the problem is still present Honestly I don't know how to fix this situation. With Xcode 15 I had not any problem with that but I am not sure if Xcode 16.0 was runing without problems because I didn't need to use this functionality in those months Here is my code for a UITest: import XCTest final class ScreenshotsUITests: XCTestCase { let app = XCUIApplication() let device = "iPhone16" override func setUpWithError() throws { continueAfterFailure = true } override func tearDownWithError() throws {} @MainActor func testEnglishScreens() throws { let lang = "en" app.launchArguments.append("UITestMode") app.launchArguments += ["-AppleLanguages", "(en)"] app.launchArguments += ["-AppleLocale", "en_US"] app.launch() executeTestsForMenus(lang: lang, backLabel: "Back") executeTestForMatch(lang: lang) } @MainActor func testSpanishScreens() throws { let lang = "es" app.launchArguments.append("UITestMode") app.launchArguments += ["-AppleLanguages", "(es)"] app.launchArguments += ["-AppleLocale", "es_ES"] app.launch() executeTestsForMenus(lang: lang, backLabel: "Atrás") executeTestForMatch(lang: lang) } private func executeTestForMatch(lang: String) { let startButton = app.buttons["start-button"] startButton.tap() let key4 = app.buttons["key-4"] XCTAssertTrue(key4.waitForExistence(timeout: 30), "Key 4 in match screen is not found") key4.tap() let key2 = app.buttons["key-2"] XCTAssertTrue(key2.exists, "Key 2 in match screen is not found") key2.tap() makeScreenShot("playing", lang: lang) let closeButton = app.buttons["close-button"] XCTAssertTrue(closeButton.exists, "Close button in match screen is not found") closeButton.tap() } private func executeTestsForMenus(lang: String, backLabel: String) { let mainHeader = app.staticTexts["Math match"] XCTAssertTrue(mainHeader.exists, "Header in main screen is not found") makeScreenShot("mainMenu", lang: lang) let settingsButton = app.buttons["settings-button"] XCTAssertTrue(settingsButton.exists, "Settings button in main screen is not found") settingsButton.tap() makeScreenShot("Settings", lang: lang) let backButton = app.buttons[backLabel] XCTAssertTrue(backButton.exists, "Back button in match screen is not found") backButton.tap() let helpButton = app.buttons["help-button"] XCTAssertTrue(helpButton.exists, "Help button in main screen is not found") helpButton.tap() makeScreenShot("Help", lang: lang) backButton.tap() let scoreButton = app.buttons["score-button"] XCTAssertTrue(scoreButton.exists, "Scores button in main screen is not found") scoreButton.tap() makeScreenShot("Scores", lang: lang) backButton.tap() let playButton = app.buttons["play-button"] XCTAssertTrue(playButton.exists, "Play button in main screen is not found") playButton.tap() makeScreenShot("matchBuilder", lang: lang) let startButton = app.buttons["start-button"] XCTAssertTrue(startButton.exists, "Start button in match builder screen is not found") } private func makeScreenShot(_ name: String, lang: String) { takeScreenshot(app, named: "\(lang)-\(name)-\(device)") } } import XCTest extension XCTestCase { func takeScreenshot(_ app: XCUIApplication, named name: String, fullScreen: Bool = false) { let screenshot: XCUIScreenshot if fullScreen { screenshot = app.windows.firstMatch.screenshot() } else { screenshot = XCUIScreen.main.screenshot() } let screenshotAttachment = XCTAttachment( uniformTypeIdentifier: "public.png", name: "screenshot-\(name).png", payload: screenshot.pngRepresentation, userInfo: nil) screenshotAttachment.lifetime = .keepAlways add(screenshotAttachment) } } and here is the content of my testplan file: { "configurations" : [ { "id" : "35BC7C0B-9A5A-4027-9F30-36958C4C1AAF", "name" : "Test Scheme Action", "options" : { "preferredScreenCaptureFormat" : "screenshot", "testExecutionOrdering" : "random", "uiTestingScreenshotsLifetime" : "keepAlways", "userAttachmentLifetime" : "keepAlways" } } ], "defaultOptions" : { "targetForVariableExpansion" : { "containerPath" : "container:myAppProject.xcodeproj", "identifier" : "B27D1B022CA00314001A259B", "name" : "MyAppProject" } }, "testTargets" : [ { "parallelizable" : true, "target" : { "containerPath" : "container:MyAppProject.xcodeproj", "identifier" : "B27D1B122CA00315001A259B", "name" : "MyAppProjectTests" } }, { "parallelizable" : true, "target" : { "containerPath" : "container:MyAppProject.xcodeproj", "identifier" : "B27D1B1C2CA00315001A259B", "name" : "MyAppProjectUITests" } } ], "version" : 1 } I made tests with old projects in my machine and those projects have the same problem with screenshot files in the xcresult bundles I don't know if the problem is in my machine, my Xcode, MacOS or other ting. I don't know how to fix this problem Please, can anyone help me? Thanks in advance
0
0
41
1d
Unable to inspect SwiftUI view embedded inside UITableView
We have been trying to migrate screens that were developed using UITool Kit to SwiftUI. In the process we have some screens that have SwiftUI embedded inside the UITool kit view. Our developers have defined accessibility ids for all elements in these views and these are inspectable using the native iOS xcode inspector. However when i try inspecting it with the appium inspector i get an empty list with no elements in the hierarchy tree. Attaching a screenshot of the element when inspecting through the native xcode accessibility inspector, Attaching a screenshot of the same screen when inspected through the appium inspector, Also tried printing the XCTest UI dump using appium method, `driver().executeScript("mobile:source", Map.ofEntries(Map.entry("format","description"))) The UI tree i get is the same that i get when inspecting through the appium inspector. Requesting support from the Apple team based on this ticket, [https://github.com/appium/appium/issues/20759)
0
0
61
1d
What's the best way to support Genmoji with SwiftUI?
I want to support Genmoji input in my SwiftUI TextField or TextEditor, but looking around, it seems there's no SwiftUI only way to do it? If none, it's kind of disappointing that they're saying SwiftUI is the path forward, but not updating it with support for new technologies. Going back, does this mean we can only support Genmoji through UITextField and UIViewRepresentable? or there more direct options? Btw, I'm also using SwiftData for storage.
0
0
94
2d
Swift UI Chart Accessibility issue
Hi Team, We are integrating SwiftUI's Charts BarMark, UI looks good but when we try setting up custom ADA it doesn't reflect/override the accessibility label/value we set manually. Is it iOS defect or is there any workaround? Thanks in advance. Sample: Chart(data) { BarMark( x: .value("Category", $0.department), y: .value("Profit", $0.profit) ) .foregroundStyle(by: .value("Product Category", $0.productCategory)) .accessibilityIdentifier("BarMark") .accessibilityLabel("Dep: \($0.department)") .accessibilityValue("Profile: \($0.profit) Category: \($0.productCategory)") }
0
0
149
2d
SwiftUI DatePicker size not configurable
Hey guys, I'm totally new to Swift programming and I'm setting up a view for registering users. I use a VStack to organize the TextFields as well as a DatePicker, but the last one seems to be very rebellious. Here's my code: VStack { TextField("E-Mailadresse", text: $mail) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .mail) .onKeyPress(.tab, action: {hasFocus = .password; return .handled}) SecureField("Passwort", text: $password) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .password) .onKeyPress(.tab, action: {hasFocus = .name; return .handled}) TextField("Name", text: $name) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .name) .onKeyPress(.tab, action: {hasFocus = .prename; return .handled}) TextField("Vorname", text: $prename) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .prename) .onKeyPress(.tab, action: {hasFocus = .birthday; return .handled}) DatePicker("Geb.:", selection: $birthday, displayedComponents: [.date]) .datePickerStyle(.wheel) .clipped() //.focused($hasFocus, equals: .birthday) Button("Registrieren") {self.register()} .padding(.top, 20) .keyboardShortcut(.defaultAction) } .frame(width: 375) } And this is how it looks like: As you can see, neither is the DatePicker centered correctly (it's more left located) nor is it clipped (reduced). I also tried adding a .frame() to itself, then I was ably to reduce it to the preferred height, but I can' reduce its width and as a result of this, I can also not write a full label like "Date of Birth" or something, because the wheel of the DatePicker always overlays it... Is that a kind of misbehavior or am I missing something? Thank you very much in anticipation for your feedback! Kind regards Kevin
1
0
96
2d
Management of multiple root views in SwiftUI
Hey guys, I'm totally unexperienced in Swift coding and I'm doing my first steps using Swift Playgrounds on my macOS as well as on my iPadOS. I'm setting up a simple App that can be divided in 4 main categories (Splash, Authentication, Content, Setup). Each category (except the Splash as the short intro when running the app) can have a NavigationStack (e. g. switching between login view, register view, forgott password view in authentication). So I thought about having a root view for each of them. My google research gave me lots of ways and hints but it's not clear at all for me if I should and how I should do this. I often read about a RootViewController but I guess that's UIKit stuff and nothing for SwiftUI. Then I read about delegates and such. Then, I read an article that exactly fits my goals and I just liked to get your opinion what you think about this way to solve my plan: First of all, I define a separate class for a appRootManager: final class appRootManager: ObservableObject { enum eRootViews { case Splash, Authentification, Content, Setup } @Published var currentRoot: eRootViews = .Splash } The main app file looks like this: @main struct MyApp: App { @StateObject private var oRootManager = appRootManager() var body: some Scene { WindowGroup() { Group { switch oRootManager.currentRoot { case .Splash: viewSplash() case .Authentification: viewLogin() case .Content: viewContent() case .Setup: viewSetup() } } .environmentObject(oRootManager) .modelContainer(for: [Account.self]) } } } In each of the for root view files (e. g. Splash view) I make the appRootManager addressable and switch the root view by updating the enum value, like for example: struct viewSplash: View { @EnvironmentObject private var oRootManager: appRootManager var body: some View { ZStack { Color.blue .ignoresSafeArea() Text("Hello World") .font(.title) .fontWeight(.semibold) .foregroundColor(.white) } .onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + 3) { withAnimation(.spring()) {oRootManager.currentRoot = .Authentification} } } } } It works fine and does exactly what I like to have (when I run the app out of Swift Playgrounds). I'm just wondering why it does not work in the App Preview in Swift Playgrounds and this is why I'd like to have your opinion to the way I solve my plan. I'm very happy for any feedback. Thanks a lot in anticipation! Kind regards Kevin
1
0
94
1d
Hi, I have an issue with app preview
I can't seem to access preview for any of my views in any of my swift projects at all (using Mac to code and using iPhone 16 pro as preview and simulation, simulation can work), even after restarting Mac and Xcode itself. The preview section has a popup saying "Cannot preview in this file, unexpected error occured" (for every file), please tell me what is wrong and help me solve it to see the preview, thank you! details
1
0
102
2d
Unexpected system behavior with 'getifaddrs'
On iOS beta, monitoring network usage using the getifaddrs API sporadically causes system volume spikes. This happens even though the application does not interact with any audio-related code. The issue persists across different polling intervals (e.g., 0.05s to 1s) and only occurs when invoking getifaddrs. Replacing the API calls with mock data eliminates the problem, suggesting a potential issue with getifaddrs in the beta environment. The application updates UI elements based on network activity, but the volume spikes occur independently of UI or other observable app behavior. Steps to Reproduce: Create an app that monitors network usage using the getifaddrs API. Fetch network statistics on a timer (e.g., every 0.05 seconds). Observe system behavior while running the app on iOS beta. Note sporadic volume spikes during app runtime. Expected Result: Polling network usage with getifaddrs should not affect system volume or other unrelated resources. Actual Result: System volume spikes occasionally when network statistics are retrieved using getifaddrs. iOS 18.2 Beta, Tested on physical device ( iPhone 15 Pro )
1
0
107
3d
Label cannot export localized string key
Hello all. This is my code snippet. RecordListView() .tabItem { Label("Record List", systemImage: "list.clipboard") } .tag(Tab.RecordList) When I export localizations, there is no Record List in the .xcloc file. Then I use LocalizedStringKey for Label and export localizations file, the code is as follows: let RecordsString:LocalizedStringKey = "Tab.Records" RecordListView() .tabItem { Label(RecordsString, systemImage: "list.clipboard") } .tag(Tab.RecordList) There is still no Tab.Records.
1
0
137
3d
SwiftUI/WebKit Allowing popups and links
We are using an imbedded WKWebView in a SwiftUI view. There are links within the pages being viewed - they are company pages - and some link to other pages as well as open named (or unnamed) browser tabs. In our implementation, when there is a named (or unnamed) link to another browser tab, the view does not do anything. Any ideas on how to allow tabs to open in some manner and allow the users to access the links?
2
0
92
2d
SwiftUI Color Issue
I have ran into an issue that is illustrated by the code in the following GitHub repository. https://github.com/dougholland/ColorTest When a SwiftUI color originates from the ColorPicker it can be persisted correctly and renders the same as the original color. When the color originates from the MapFeature.backgroundColor, it is always rendered with the light appearance version of the color and not the dark appearance version. The readme in the GitHub repo has screenshots that show this. Any assistance would be greatly appreciated as this is affecting an app that is in development and I'd like to resolve this before the app is released. If this is caused by a framework bug, any possible workaround would be greatly appreciated also. I suspect it maybe a framework issue, possibly with some code related to the MapFeature.backgroundColor, because the issue does not occur when the color originates from the ColorPicker.
0
1
105
4d
DocumentGroup with SwiftData BUG!!!!! (modelContext cannot save and querry)
This is a critical bug with Document-Based Apps (SwiftData). If you download the WWDC 2023 sample code for"Building a document-based app using SwiftData" , open it in Xcode 16.1, and run it on an iOS 18+ simulator, you'll encounter a major issue. When you exit a document and reopen it, you'll find that the changes you just made were not saved. iOS 18 has effectively rendered last year's WWDC 2023 sample code obsolete! Has anyone managed to successfully save data in a Document-Based App using SwiftData?
0
0
124
5d
MacOS CloudKit production environment is not working properly
My macOS app is developed using SwfitUI, SwiftData, and CloudKit. In the development environment, CloudKit works well. Locally added models can be quickly viewed in the CloudKit Console. macOS app and iOS app with the same BundleID can also synchronize data normally when developing locally. However, in the production environment, the macOS app cannot synchronize data with iCloud. But iOS app can. The models added in the production environment are only saved locally and cannot be viewed in CloudKit Console Production. I am sure I have configured correctly, container schema changes to deploy to the Production environment. I think there may be a problem with CloudKit in macOS. Please help troubleshoot the problem. I can provide you with any information you need. var body: some Scene { WindowGroup { MainView() .frame(minWidth: 640, minHeight: 480) .environment(mainViewModel) } .modelContainer(for: [NoteRecord.self]) } I didn't do anything special. I didn’t do anything special. I just used SwiftData hosted by CloudKit.
2
0
125
2d
[iOS 18.2 Beta] LazyVGrid within NavigationStack breaks animations
Hello. There seems to be a bug specifically in the iOS 18.2 (both Beta 1 and 2) and not seen in the previous versions. The bug is: when LazyVGrid is nested inside NavigationStack and some elements of the LazyVGrid have animations, navigating into any nested view and then going back to the initial view with the LazyVGrid causes all animations to stop working. Here is the example code inline: struct ContentView: View { @State private var count: Int = 0 var body: some View { NavigationStack { LazyVGrid( columns: Array( repeating: GridItem(spacing: 0), count: 1 ), alignment: .center, spacing: 0 ) { VStack { Text(String(count)) .font(.system(size: 100, weight: .black)) .contentTransition(.numericText()) .animation(.bouncy(duration: 1), value: count) Button("Increment") { count += 1 } NavigationLink(destination: { Text("Test") }, label: { Text("Navigate") }) } } } .padding() } } Once you run the application on iOS 18.2 Beta (I've tried on a real device only), the steps to reproduce are: Tap on the "Increment button" You should see the number change with an animation Tap on the "Navigate" button Tap "Back" to go to the initial screen Tap "Increment" again The number changes without an animation I can confirm that this affects not only .contentTransition() animation but any animation within the LazyVGrid, I've tested this in my real app. Let me know if I can provide more details. Thank you!
4
0
142
20h