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

SwiftUI Documentation

Posts under SwiftUI tag

2,342 Posts
Sort by:
Post not yet marked as solved
2 Replies
137 Views
Hi all apple devs! I am a young developer who is completely new to everything programming. I am currently trying to develop an app where I want to use visionkit, but I can't for the life of me figure out how to implement its features. I've been stuck on this for several days, so I am now resorting to asking all of you experts for help! Your assistance would be immensely appreciated! I started to develop the app trying to exclusively use swiftUI to futureproof my app. Upon figuring out what visionkit is, to my understanding it is more compatible with UIkit? So I rewrote the part of my code that will use visionkit into a UIkit based view, to simplify the integration of visionkits features. It might just have overcomplicated my code? Can visionkit be easily implemented using only swiftUI? I noticed in the demo on the video tutorial the code is in a viewcontroller not a contentview, is this what makes my image unresponsive? My image is not interactable like her demo in the video, where in my code do I go wrong? Help a noob out! The desired user flow is like this: User selects an image through the "Open camera" or "Open Camera Roll" buttons. Upon selection the UIkit based view opens and the selected image is displayed on it. (This is where I want to implement visionkit features) User interacts with the image by touching on it, if touching on a subject, the subject should be lifted out of the rest of the image and be assigned to the editedImage, which in turn displays only the subject without the background on the contentview. (For now the image is assigned to editedimage by longpressing without any subjectlifting since I cant get visionkit to work as I want) Anyways, here's a code snippet of my peculiar effort to implement subject lifting and visionkit into my app:
Posted
by emol.
Last updated
.
Post not yet marked as solved
2 Replies
82 Views
I am developing an app in mixed immersive native app on Vision Pro. In my RealityView, I add my scene by content.add(mainGameScene). Normally the anchored position (original coord) should be the device position but on the ground (with y == 0 on the ground). At least this is how I understand the RealityViewContent works. So if I place something at position (0, 0, -1.0), the object should be in the front of you but on the floor (z axis is pointing backwards) However recently I load a different scene and I add that with same code, content.add(mainGameScene), something has changed, my scene randomly anchored on the floor or ceiling, according to the places I stand or sit. When I open Visualizations of my anchoring point, I could see that anchor point I am using is on the ceiling. The correct one (around my foots) is left over there. How could I switch to the correct anchored position? Or does any setting can change the behavior of default RealityViewContent?
Posted
by milanowth.
Last updated
.
Post not yet marked as solved
4 Replies
245 Views
hi I have been using WKWebView embedded in a UIViewRepresentable for displaying inside a SwiftUI View hierarchy, but when I try the same code on 17,5 beta (simulator) the code fails. In fact, the code runs (no exceptions raised or anything) but the web view does not render. In the console logs I see: Warning: -[BETextInput attributedMarkedText] is unimplemented Error launching process, description 'The operation couldn’t be completed. (OSStatus error -10814.)', reason '' The code I am using to present the view is: struct MyWebView: UIViewRepresentable { let content: String func makeUIView(context: Context) -> WKWebView { // Javascript that disables pinch-to-zoom by inserting the HTML viewport meta tag into <head> let source: String = """ var meta = document.createElement('meta'); meta.name = 'viewport'; meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'; var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '*:focus{outline:none}body{margin:0;padding:0}'; var head = document.getElementsByTagName('head')[0]; head.appendChild(meta); head.appendChild(style); """ let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) let userContentController: WKUserContentController = WKUserContentController() let conf = WKWebViewConfiguration() conf.userContentController = userContentController userContentController.addUserScript(script) let webView = WKWebView(frame: CGRect.zero /*CGRect(x: 0, y: 0, width: 1000, height: 1000)*/, configuration: conf) webView.isOpaque = false webView.backgroundColor = UIColor.clear webView.scrollView.backgroundColor = UIColor.clear webView.scrollView.isScrollEnabled = false webView.scrollView.isMultipleTouchEnabled = false if #available(iOS 16.4, *) { webView.isInspectable = true } return webView } func updateUIView(_ webView: WKWebView, context: Context) { webView.loadHTMLString(content, baseURL: nil) } } This has been working for ages and ages (back to at least ios 15) - something changed. Maybe it is just a problem with the beta 17.5 release?
Posted Last updated
.
Post not yet marked as solved
0 Replies
66 Views
My goal is to create Apples activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a spark effect, but I don't know how to create a custom one that fits my needs. I'm still quite new to SwiftUI animations. Does someone have an idea how to do it? VortexView(createSparkle()) { Circle() .fill(.white) .frame(width: 16) .tag("circle") } func createSparkle() -> VortexSystem { let system = VortexSystem(tags: ["circle"]) system.birthRate = 150 system.emissionDuration = 0.2 system.idleDuration = 0.5 system.lifespan = 1.5 system.speed = 1.5 system.speedVariation = 0.2 system.angle = .degrees(330) system.angleRange = .degrees(30) system.acceleration = [0, 3] system.dampingFactor = 4 system.colors = .ramp(.white, .yellow, .yellow.opacity(0)) system.size = 0.1 system.sizeVariation = 0.1 system.stretchFactor = 8 return system } Vortex project: https://github.com/twostraws/Vortex
Posted
by iRIG.
Last updated
.
Post not yet marked as solved
0 Replies
76 Views
I have a peculiar situation, where the first time I present a sheet from a Section that has the header: set, the sheet disappears by itself the first time it is presented. @State private var show = false // … List { Section { Text("foo") } header: { Text("bar") } .sheet(isPresented: $show) { Text("baz") } // just to enable Button("toggle") { show = true } } In Xcode I get this warning when I present the sheet (taken from our live app): Attempt to present <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x10a819e00> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x10a020600> (from <_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x10a0cba00>) while a presentation is in progress. Tested on iOS 17.4.1, iPadOS 17.4.0 (Simulator), Xcode 15.3 Previews.  Circumstances The circumstances are as following: a Section has to be in a List, and have content:, and header: or footer: set to something, and have the .sheet(…) set on the section itself. The problem does not occur with these sections: Section { Text("…") } Section { } footer: { Text("…") } Section { Text("…") } header: { } … but the following views have the sheet disappear the first time it is presented: Section { Text("…") } header: { Text("…") } Section { Text("…") } footer: { Text("…") } Section { Text("…") } header: { Text("…") } footer: { Text("…") } Is this a known issue, and are there any known workarounds to present from a Section? My best guess is to move the .sheet(…) to the parent container, but I'll have to restructure part of my code quite a bit to do so 😕
Posted
by vladimirs.
Last updated
.
Post not yet marked as solved
0 Replies
36 Views
My ".navigationTitle" is on my physical iPhone 14 and Simulator iPhone 15 not displayed, on Xcode Preview Screen is it displayed perfect. Why is it and what can i do that is displayed on my iPhone 14.
Posted Last updated
.
Post not yet marked as solved
0 Replies
44 Views
SwiftUI's PhotoPicker doesn't fit into the screen when I place it on a popover and click on it to select a photo. The relevant code I use: .popover( isPresented: $showAttachments ) { VStack(alignment: .leading, spacing: 20) { // ... PhotosPicker(selection: $photos) { HStack { Image(systemName: "photo") Text("Media") } } } } It seems like the photo picker is positioned relative to the popover position and I can't find any configuration options regarding to its' positioning. How to position the PhotoPicker correctly?
Posted Last updated
.
Post not yet marked as solved
1 Replies
433 Views
I'm using NavigationLink(value:label:) and .navigationDestination(for:destination:) in my SwiftUI watchOS app. However navigating in the app causes the system to emit the following errors to the console: <NavigationHostingControllerCache>: MISS at depth 1 in free stack [NavigationHostingControllerCache_UIKit] <_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x125015000> containment skipped because sourceNavigationController or destination were nil or sourceNavigationController was equal to destination [NavigationHostingControllerCache_UIKit] Eject called for index: depth 1 in free stack Library: SwiftUI, Subsystem: com.apple.SwiftUI , Category: Invalid Configuration The navigation itself does work fine. I'm wondering there's something I can do to fix it or if this is an internal issue of the SwiftUI framework and cannot be addressed by me? (i.e. I can ignore this)
Posted Last updated
.
Post not yet marked as solved
0 Replies
43 Views
i'm struct dynamic island detail content dynamicIsland: { context in DynamicIsland { expandedContent(context: context) } compactLeading: { .... } compactTrailing: { ... } i want show different content based on context. private func expandedContent(context: ActivityViewContext<xxxx>)->DynamicIslandExpandedContent<some View> { if (context.state.style == 0) { return expandedControlContent1(context: context) } else if (context.state.style == 1) { return expandedControlContent2(context: context) } else { return expandedControlContent3(context: context) } } compiles error Function declares an opaque return type 'some View', but the return statements in its body do not have matching underlying types
Posted
by Highmore.
Last updated
.
Post not yet marked as solved
0 Replies
55 Views
Here is the view in which it works struct MileageHistoryView: View { let vehicle: Vehicle init(for vehicle: Vehicle) { self.vehicle = vehicle } @Environment(\.modelContext) private var context @Environment(\.editMode) private var editMode var sorted: [Mileage] { guard let history = vehicle.mileageHistory else { return [] } return history.sorted(by: { $0.timestamp > $1.timestamp }) } var body: some View { List { ForEach(sorted) { mileage in MileageListItem(mileage, editing: Binding(get: {editMode?.wrappedValue.isEditing ?? false}, set: {_ in })) } .onDelete(perform: deleteMileage) .deleteDisabled(editMode?.wrappedValue.isEditing ?? false ? false : true) } .id(editMode?.wrappedValue.isEditing) .navigationTitle("Mileage History") .scrollContentBackground(.hidden) .toolbar { ToolbarItem(placement: .topBarTrailing, content: { EditButton() }) } } } Here is the other view where it doesn't work. In this view, it seems like when the EditButton is pressed, no change is happening with the editMode so deleteDisabled() is always set to true. struct VehiclesView: View { @Environment(\.modelContext) private var context @Environment(\.editMode) private var editMode // Local @Query private var vehicles: [Vehicle] @State private var addVehicle = false @AppStorage("vehicle-edit-alert") private var showEditAlert = true @State private var editAlert = false @State private var editShown = false var body: some View { NavigationStack { List { ForEach(vehicles) { vehicle in NavigationLink(destination: VehicleView(vehicle), label: { VehicleListItem(vehicle) }) } .onDelete(perform: deleteVehicle) .deleteDisabled(self.editMode?.wrappedValue.isEditing ?? false ? false : true) } .id(self.editMode?.wrappedValue.isEditing) .scrollContentBackground(.hidden) .navigationTitle("Vehicles") .toolbar { ToolbarItem(placement: .topBarLeading, content: { if showEditAlert && !editShown { Button("Edit") { editAlert = true } } else { EditButton() } }) ToolbarItem(placement: .topBarTrailing, content: { Button(action: { addVehicle.toggle() }, label: { Image(systemName: "plus") }) .accessibilityHint("Opens the view to add a Vehicle") }) } .fullScreenCover(isPresented: $addVehicle, content: { VehicleEditor() }) } .scrollIndicators(.hidden) } } When EditButton() is used in the second view the list item is grayed out, but the buttons to delete aren't there. Does anybody know why this is happening?
Posted
by Xavier-k.
Last updated
.
Post not yet marked as solved
1 Replies
77 Views
We've been working on a SwiftUI app that randomly crashes with an exception. When navigating from one view to another, a rare exception is thrown, maybe every 1 / 200 times or so: <SwiftUI.UIKitNavigationController: 0x109888400> is pushing the same view controller instance (<_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x10792d400>) more than once which is not supported and is most likely an error in the application : com.<companyName>.<appName> We haven't coded anything to directly push an instance of a view controller outside of what SwiftUI is doing. It seems to happen when the user taps on a NavigationLink view. It happens both in simulator and on device. Does anyone know what might cause this?
Posted
by GBecker.
Last updated
.
Post not yet marked as solved
0 Replies
53 Views
Dear Community, I have a use case where I have to present multiple sheets of different, non-resizable heights from a View. It seems like when multiple .presentationDetents() are specified and you control the current detent with selection:, SwiftUI always allows the user to resize the sheet, even if .presentationDragIndicator(.hidden) is set. In my use case, however, I wouldn't like to let the user do so, because this would result in a small view presented on a large sheet with lot of empty space around. Specifying just one presentationDetent and changing it or its height programmatically doesn't seem to work: the change does not reflect immediately, even if the view in the sheet is given a new id() every time. The only thing I could come up with is a custom detent as follows: import SwiftUI public class DynamicDetent: CustomPresentationDetent { static var height: CGFloat = 80 public static func height(in context: Context) -> CGFloat? { return height } } extension PresentationDetent { static let dynamic = Self.custom(DynamicDetent.self) } As the height() functon is being called every time the sheet is being displayed, setting DynamicDetent.height before displaying a new sheet works. Is there any other, less hacky way to achieve the same result?
Posted Last updated
.
Post not yet marked as solved
0 Replies
52 Views
Hello all, if I enable the .chartScrollableAxes(.horizontal) and .chartXVisibleDomain(length: length) for a chart view to zoom in the screenshot of the view misses the graphs. I use this extension: `extension View { @MainActor func snapshot() { let renderer = ImageRenderer(content: self) if let exportImage = renderer.nsImage { let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects([exportImage]) } } }` The screenshot is taken with: Button("Snap") { let view = ChartView(text: $statusText, length: $chartLength) .padding() .frame(width: 1500, height: 500) view.snapshot() } If I omit .chartScrollableAxes(.horizontal) the snapshot is ok and the graphs are visible in the image but then a zoom is not possible and the whole range is shown. Any ideas?
Posted
by Zettifour.
Last updated
.
Post not yet marked as solved
0 Replies
49 Views
Hello, I have a question. I have a LookAroundPreview, that loads correctly a scene, and when I tap on it, it natively shows a view I can navigate in, and that I can close. All that is ok. However, when I want to display that same LookAroundPreview in a fullScreenCover (because my app needs it for navigation purposes), it directly shows the navigatable View with the closeButton. That I don't want. Is there an option to pass, that I missed? Is this a bug of the LookAroundPreview? Or is this wanted by Apple devs? Thank you very much for your help, Sincerely import SwiftUI struct ContentView: View { @State private var displayFullScreen = false //AppleLookAroundView is just a wrapper around native LookAroundPreview, that loads a NYC coordinate var body: some View { VStack { AppleLookAroundView() Spacer() Button("Display fullScreen cover") { displayFullScreen = true } Spacer() } .fullScreenCover(isPresented: $displayFullScreen) { VStack { AppleLookAroundView() Text("⬆ It somehow detects it is in a fullScreenCover and unwantingly change its display") } } } } import SwiftUI import MapKit import CoreLocation struct AppleLookAroundView: View { @State private var scene: MKLookAroundScene? let coordinate = CLLocationCoordinate2D(latitude: 40.651238394229324, longitude: -73.96432239237737) var body: some View { LookAroundPreview(scene: $scene, allowsNavigation: true, badgePosition: .bottomTrailing) .task { do { scene = try await fetchScene(for: coordinate) } catch { print("Couldn't fetch scene") } } .frame(height: 300) } private func fetchScene(for coordinate: CLLocationCoordinate2D) async throws -> MKLookAroundScene? { let lookAroundScene = MKLookAroundSceneRequest(coordinate: coordinate) let scene = try await lookAroundScene.scene return scene } } ![]("https://developer.apple.com/forums/content/attachment/a10a7701-dd8c-4d83-9a03-848cf0373417" "title=Capture d’écran 2024-04-24 à 12.56.46.png;width=898;height=1860") `` ![]("https://developer.apple.com/forums/content/attachment/d54f7fe1-aac8-4280-ab97-663f0bdd440f" "title=Capture d’écran 2024-04-24 à 12.56.34.png;width=924;height=1882") `
Posted Last updated
.
Post not yet marked as solved
0 Replies
40 Views
The regular case. Open a sheet by clicking a button. Next close the sheet using a Cancel button on it. The isPresented state variable is changed immediately, but while the dismissing animation isn't totally finished it's impossible to click the Button on the main parent screen and call the sheet presentation again. As I understand UIKit works differently and lets us click the Button but just calls a new modal view exactly after the previous animation is finished struct MyView: View { @State private var isPresented = false public var body: some View { VStack { Button(action: { isPresented = true }, label: { Text("Button") }) Spacer() } .sheet(isPresented: $isPresented) { sheetContent } } var sheetContent: some View { VStack { Text("Cancel") .onTapGesture { isPresented = false } Spacer() } } } @Apple Could you please fix it in SwiftUI?
Posted Last updated
.
Post not yet marked as solved
0 Replies
34 Views
Condition: We have an existing app that runs on iPhone and iPad. We want to make it compatible with macOS, along with it we want to leverage some of the macOS native components. We achieved this using macCatalyst, but now we want to build common components using swiftUI for both macOS and iOS platforms. Challenge: Using SwiftUI view for mac development Approach 1: We created a Mac bundle that contained Mac specific views (using Appkit views). This approach worked fine for creating and using components that are specific to macOS. Now while developing and using SwiftUI views in mac bundle we face following error -> (NSHostingViewController symbol not found). Approach 2: We tried creating a separate Mac app and make it part of MacCatalyst app. In this approach we were able to show NSStatusBar and add text using SwiftUI view. But the status bar appearance is inconsistent, sometimes NSStatusBar icon appears but other times it just won't appear. Can anyone help with the right approach for this scenarios
Posted Last updated
.
Post not yet marked as solved
2 Replies
339 Views
I Implement a 'SubscriptionStoreView' using 'groupID' into a project (iOS is targeting 17.2 and macOS is targeting 14.1).Build/run the application locally (both production and development environments will work fine), however once the application is live on the AppStore in AppStoreConnect, SubscriptionStoreView no longer shows products and only shows 'Subscription Unavailable' and 'The subscription is unavailable in the current storefront.' - this message is shown live in production for both iOS and macOS targets. There is no log messages shown in the Console that indicate anything going wrong with StoreKit 2, but I haven't made any changes to my code and noticed this first start appearing about 5 days ago. I expect the subscription store to be visible to all users and for my products to display. My application is live on both the iOS and macOS AppStores, it passed App Review and I have users who have previously been able to subscribe and use my application, I have not pushed any new changes, so something has changed in StoreKit2 which is causing unexpected behaviour and for this error message to display. As 'SubscriptionStoreView' is a view provided by Apple, I'm really not sure on the pathway forward other than going back to StoreKit1 which I really don't want to do. Is there any further error information that can be provided on what might be causing this and how I can fix it? (I have created a feedback ticket FB13658521)
Posted
by Lukesrad.
Last updated
.