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

SwiftUI Documentation

Posts under SwiftUI tag

2,339 Posts
Sort by:
Post not yet marked as solved
2 Replies
128 Views
Please take a look at the following simple SwiftUI View: struct ContentView: View { var body: some View { ForEach(1...1, id: \.self) { i in subview(i) } } func subview(_ i: Int) -> some View { print("creating subview \(i)") return Text("Hello, world!") } } When this View is displayed, all subviews are created twice, as the print statements show. (Unfortunately the Apple Developer Forums UI does not let me attach my sample Xcode project.) This happens on macOS 14.4.1. Am I doing something wrong or is this a SwiftUI bug? (In a real-world application the View creation can be expensive…)
Posted
by rx8.
Last updated
.
Post not yet marked as solved
0 Replies
97 Views
I have view hierarchy like this: NavigationView { VStack { ScrollView { // some content } .background(NavigationLink(destination: MyView(), isActive: $isActive) { EmptyView() }) // snipped } } When the user follows the navigation link to MyView, by default NavigationBar and MyView is laid out like in a VStack. How can I make them like in a ZStack(alignment: .topLeading) ? i.e. I like MyView extends beneath the NavigationBar. Here is the MyView: GeometryReader { geo in HStack { // some content } .onAppear { hideNavigationbar = false } .onTapGesture(perform: { hideNavigationbar.toggle() }) .navigationBarHidden(hideNavigationbar) .navigationBarTitleDisplayMode(.inline) // snipped } The problem is, when hideNavigationbar toggles, MyView would shift up and down because its height would change. I want NavigationBar sits on top of MyView like in a ZStack so that when NavigationBar hides, MyView will not shift (only uncover its top portion). What is the proper way to achieve that? XCode: 15.3 using SwiftUI iOS: 15
Posted Last updated
.
Post not yet marked as solved
2 Replies
602 Views
Hi, I am running into an error on XCode 15 (iOS 17+). When I am trying to play an iframe on the app. I see this error popup. Warning: -[BETextInput attributedMarkedText] is unimplemented Failed to request allowed query parameters from WebPrivacy. How do I fix this issue? I never saw this before so I am sure it is new. The app use to run fine as well.
Posted Last updated
.
Post marked as solved
1 Replies
112 Views
I have a two-view app where the main view is a procedural animation and a secondary view controls settings for the animation. I want to use Play/Pause to toggle between the views, but can't figure out how to do this. Ideally the main view does not have any visible control and the whole screen can be dedicated to the animation view. Attaching onPlayPauseCommand to the main view does not work. I've also tried managing focus using onFocus without success. I'm open to other ways to toggle between the main and settings views, it's just that Play/Pause seems the most intuitive.
Posted Last updated
.
Post marked as solved
3 Replies
190 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
0 Replies
150 Views
I've found a strange leak, that looks like a bug. When we open two sheets, or fullscreenCovers and the last one has a TextField, then after closing both, @StateObject property is not released. If you delete TextField, there will be no memory leak. It works well and memory is releasing on iOS 16 built with Xcode 15 (simulators) Memory is leaking and not releasing on iOS 17 built with Xcode 15 (simulators, device 17.4.1) import SwiftUI struct ContentView: View { @State var isFirstOpen: Bool = false var body: some View { Button("Open first") { isFirstOpen = true } .sheet(isPresented: $isFirstOpen) { FirstView() } } } struct FirstView: View { @StateObject var viewModel = LeakedViewModel() var body: some View { ZStack { Button("Open second") { viewModel.isSecondOpen = true } } .sheet(isPresented: $viewModel.isSecondOpen) { SecondView(onClose: { viewModel.isSecondOpen = false }) } } } final class LeakedViewModel: ObservableObject { @Published var isSecondOpen: Bool = false init() { print("LeakedViewModel init") } deinit { print("LeakedViewModel deinit") } } struct SecondView: View { @State private var text: String = "" private let onClose: () -> Void init(onClose: @escaping () -> Void) { self.onClose = onClose } var body: some View { Button("Close second"){ onClose() } TextField("text: $text", text: $text) // Comment TextField and the leak will disappear, viewModel deinit called } } @main struct LeaksApp: App { var body: some Scene { WindowGroup { ContentView() } } } May be related to https://forums.developer.apple.com/forums/thread/738840
Posted
by Andreynt.
Last updated
.
Post not yet marked as solved
2 Replies
217 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
4 Replies
440 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
121 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
146 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
1 Replies
89 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
91 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
529 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
104 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
102 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
2 Replies
173 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
113 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
108 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
.