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

SwiftUI Documentation

Posts under SwiftUI tag

2,332 Posts
Sort by:
Post not yet marked as solved
2 Replies
1k Views
Since Xcode 15 beta 5, making a class with the @Observable macro no longer requires all properties to have an initialization value, as seen in the video. Just put an init that collects the properties and everything works correctly. @Observable final class Score: Identifiable { let id: Int var title: String var composer: String var year: Int var length: Int var cover: String var tracks: [String] init(id: Int, title: String, composer: String, year: Int, length: Int, cover: String, tracks: [String]) { self.id = id self.title = title self.composer = composer self.year = year self.length = length self.cover = cover self.tracks = tracks } } But there is a problem: the @Observable macro makes each property to integrate the @ObservationTracked macro that seems not to conform the types to Equatable, and in addition, to Hashable. Obviously, being a feature of each property, it is not useful to conform the class in a forced way with the static func == or with the hash(into:Hasher) function that conforms both protocols. That any class we want to be @Observable does not conform to Hashable, prevents any instance with the new pattern to be usable within a NavigationStack using the data driven navigation bindings and the navigationDestination(for:) modifier. I understand that no one has found a solution to this. If you have found it it would be great if you could share it but mainly I am making this post to invoke the mighty developers at Apple to fix this bug. Thank you very much. P.S. - I also posted a Feedback (FB12535713), but no one replies. At least that I see.
Posted
by jcfmunoz.
Last updated
.
Post not yet marked as solved
3 Replies
136 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
3 Replies
45 Views
Hi everyone ... i am pretty new to IOS dev, so any help would be great. I am trying to send a string "apple" from UIviewcontroller one to the UIviewcontroller sixth. I am able send the string "apple" from one UIviewcontroller to the next. But then i will have to repeat it again and again in all the views. Is there anyway i can send it directly to the sixth UIviewcontroller ?
Posted
by sonam93.
Last updated
.
Post not yet marked as solved
1 Replies
234 Views
Using SwiftData for a MacOS app I have a working Table but I'd like to add recursion to the rows so instead of stopping at the first child level I can get to grandchildren, etc. Tried creating a separate func that calls itself but cannot get working syntax, possibly because this is happening inside a DisclosureTableRow or I just have bad syntax. Instead of calling TableRow(childAccount) I'd like to be able to call a recursive function which determines if each child is treated as a parent or not until there are no more grandchildren. Each Account class object has .parent: Account, .children: [Account], and .isExpanded:Bool (required by the DisclosureTableRow but not changed here). This is the working non-recursive code: ForEach(theAccounts.sorted(using: sortOrder)) { account in // Make this account bindable so can use .isExpanded directly @Bindable var account = account // Check if the account is not a child of any other account to avoid duplcates, if !theAssetAccounts.contains(where: { $0.children?.contains(account) ?? false }) { // If the account has children, display them in a DisclosureTableRow… if let children = account.children, !children.isEmpty { DisclosureTableRow(account, isExpanded: $account.isExpanded) { ForEach(children) { childAccount in TableRow(childAccount) } } } else { // …or if the account has no children, display it in a simple TableRow TableRow(account) } } } } First the singleton theMotherAccount is at the top level then we iterate over an array of other accounts, theAccounts, showing only those that are not themselves children. Any children are then surfaced as part of another DisclosureTableRow. I thought I could just create a recursive func to return either a DisclosureTableRow or a TableRow but have not been able to find acceptable syntax. This is what I thought ought to work: if let children = account.children, !children.isEmpty { return DisclosureTableRow(account, isExpanded: Bindable(account).isExpanded) { ForEach(children) { child in recursiveAccountRow(account: child) } } } else { return TableRow(account) } }
Posted
by pikes.
Last updated
.
Post not yet marked as solved
0 Replies
34 Views
Hi, Per Apple the isStationary value is supposed to set to true when the device is stationary. I am trying to get a better understanding of when and how this status is changed. When and how does Apple decide when to set this to true and what is the threshold by which it is set to false. Right now when I start my app and use it is set from true to false instantly. let updates = CLLocationUpdate.liveUpdates() for try await update in updates { self.isStationary = update.isStationary I would love to know by what criteria it sets it to true otherwise I'm collecting a lot of zero speed very slight to no movements in latitude and longitude that I have to make some assumptions about filtering out of what I capture. I can't seem to find any mention of this or use case examples in any of the usual sources for examples despite having been introduced at the last WWDC 2023. Any help here would be appreciated.
Posted Last updated
.
Post not yet marked as solved
1 Replies
57 Views
I am trying add Sign in with Apple but when I attempt to capability in my app nothing happens in the list does apple not able to provide this feature yet in Vision OS or is there any bug or may be ami missing something which does not seems?
Posted Last updated
.
Post marked as solved
3 Replies
135 Views
I have a driving tracking app I'm working on that properly starts tracking and logging location when the app is in the foreground or background. I use a buffer/queue to keep recent locations so when a trip ramps up to driving speed I can record that to work back to the start location just before the trip starts. This works great, however, in background mode when the user does not have the app open it will record locations but not until a significant location change is detected. The buffering I do is lost and the location only starts tracking several hundred yards or more after the trip has started. Does anyone have any suggestions or strategies to handle this chicken and the egg scenario?
Posted Last updated
.
Post not yet marked as solved
0 Replies
38 Views
Adding environment value openURL or dismiss to a View in a NavigationStack, without even using it, causes an infinite refresh loop. What doesn't work: a) struct ViewA: View { @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { ViewB() } } } struct ViewB: View { @Environment(\.openURL) var openURL var body: some View { NavigationLink("Next", value: 1) .navigationDestination(for: Int.self, destination: itemView) } func itemView(_ item: Int) -> some View { Text("Item \(item)") } } Prints ViewB: _openURL changed. infinitely. b) Passing the path to ViewB and appending the value with a Button What works: a) .navigationDestination(for: Int.self) { Text("Item \($0)") } Prints ViewB: @self, @identity, _openURL changed. ViewB: @self, _openURL changed. ViewB: _openURL changed. (3 times) b) Handling the destination on ViewA, which is not ideal for my use case. Prints ViewB: @self, @identity, _openURL changed. ViewB: _openURL changed. (5 times) While the workaround would work, it is still unclear how the environment value can cause the freeze (and eventual crash). Also that passing a function as parameter fails, while providing the destination in place does not. The code is stripped down to the minimal reproducible version. Any thoughts?
Posted
by takadeivi.
Last updated
.
Post marked as solved
2 Replies
82 Views
It is driving me crazy, because I really don't know what I am doing wrong. I have a observable class: @Observable class Variables: Identifiable { var id: UUID() var xValue: Int = 1 var yValue: Int = 1 } And a main view that calls a Subview to set the variables, using environment to set variables to the Subview, because this is a very simplified code example and in the final code lot more subview are gonna use this data. struct MainView: View { @State var vars = Variables() var body: Some View { VStack { Subview() .environment(vars) .padding() Text("Value X = \($vars.xValue)") Text("Value Y = \($vars.yValue)") } } struct Subview: View { @Environment(Variables.self) private var vars var body: Some View { VStack { TextField("xValue", value $vars.xValue, format: .number) { Text("X") } TextField("yValue", value $vars.yValue, format: .number) { Text("Y") } } } I Get this error for the TextFields: Cannot convert value of type 'Int' to expected argument type 'Binding' I just don't get it. Am I mixing up different kind of bindings, is something wrong in the definition of TextField.......................................... Please help me.
Posted
by SilkSound.
Last updated
.
Post not yet marked as solved
0 Replies
37 Views
In SwiftUI, a link is identified as both a button and link, this is during when running with VoiceOver. I know you can remove the button trait using .accessibilityRemoveTraits. However, I am sure there is a reason to it. Can somebody explain if it is genuinely a bug.
Posted
by Mayur123.
Last updated
.
Post not yet marked as solved
0 Replies
34 Views
Hello, I have a custom iOS app that takes a picture every second and uploads them to an S3 bucket. However, I was wondering if there is a way to send these images to a Mac instead via USB. Basically the app would capture a photo and send it directly to a location in Mac via USB. I couldn't find any good info online so I am not sure how realistic this is. Thanks a lot!
Posted
by gonn94.
Last updated
.
Post not yet marked as solved
1 Replies
125 Views
I need to create a carousel component with the following requirements (sorted by relevance): Objectives Every image is 16:9 aspect ratio and resizes to fit the screen. Needs a zoom and pan functionality, possibly the same way as iOS Photos app. Needs to work both in landscape and portrait mode, with a smooth transition between orientations. When orientation changes, the image needs to be rotated to preserve the center of the image (like Photos app and hyperoslo/Lightbox) The component should only take the minimum necessary space. In most use cases, such component should have other subviews both above and below. Circularity. I would like the carousel to wrap around. What I tried: Using a TabView with .tabViewStyle(PageTabViewStyle()).indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) modifiers. This didn't work: rotating the interface caused the view to get stuck between pages (it looks like it's a well known [bug]).(https://stackoverflow.com/questions/72435939/swiftui-tabview-is-not-working-properly-on-orientation-change). Implementing a single page (that is, an image view) using an UIScrollView and an UIViewRepresentable, then collecting them into an HStack. Unfortunately I need to use zoomScale and contentOffset properties of the UIScrollView outside of the UIViewRepresentable itself. The net result was that .init() was invoked for every image in the carousel at every rotation, causing severe stutters and an horrible rotation animation. Implementing the whole carousel using UIKit, and an UICollectionView, whose cells were an instance of UIScrollView. The problem is, the UIScrollView needs to recompute its constraints upon rotation but a cell is an instance of UIView, so it can't respond to rotations via viewWillTransition(to:CGSize, with: any UIViewControllerTransitionCoordinator). In the UICollectionView itself, you can only access the visible cells (one at a time is visible), and cells are cached, so even after rotating, some occasionally are presented on screen with the same appearance as before the rotation (some do, some don't, in the same UICollectionView). Also when rotating, it looks like the UIScrollView of the visible cell is being recreated, making it impossible to preserve the image center (I use this subclass of UIScrollView for this purpose). And the UICollectionView is taking the full window size, not just the bare minimum necessary space. Help: With all of this in mind, what options do I realistically have? If necessary I can raise the minimum iOS version to 16.0, even though I guess it doesn't make any significative difference since SwiftUI introduced MagnifyGesture only from iOS 17.0.
Posted Last updated
.
Post not yet marked as solved
1 Replies
155 Views
Hey folks, I need to implement a view for a live activity (so using. WidgetKit), so any UIKit/SceneKit is a non-starter. The thing to implement is a horizontal representation of a 360 degree protractor ('degree triangle'). I would like this view to be inifintely scrollable as if the user has a circular shape around their head and they can rotate their head to look at all the numbers, and when they reach 360/0, they simply continue with new round. In both directions. I've managed to get this working for the positive values by using a LazyHStack and which is populated using ForEach, using a custom class that implements RandomAccessCollection where the endIndex is Int.max (not truly infinite, but good enough). However, I can't get the scrollview/ForEach to start in the 'center' of the Int.max range (I'm sure this would cause some performance issue as well). So my question is: how to get a SwiftUI scrollview to behave like a infinite scrollview, pretty much like Josh Shaffer explained in WWDC 2011 in the session with Eliza Block called 'Advanced ScrollView Techniques'?
Posted
by Joride.
Last updated
.
Post not yet marked as solved
1 Replies
194 Views
Looking at having editable text as the detail view within a master detail interface. There are various examples out there that show how to build the NSViewRepresentable wrapper around NSTextView. e.g. https://developer.apple.com/forums/thread/125920 However, when I try to embed the NSViewRepresentable within a NavigationSplitView the various examples (and my own attempt) don't work properly. There seems to be a race condition competing to update the internal bindings. I also see updateNSView being called multiple times when only one event, say selection change, is called once. Using the SwiftUI TextEditor view actually works. (it is just so limited) When the master selected item is changed the change isn't automatically propagated through to update the Coordinator. That's because there isn't a delegate for "master did change". Take any of the TextViews on their own (not within a split view) and they work as you would expect. The SwiftUI TextEditor does this without any obvious connection to the master. So the first question is: has anybody solved this type of problem? I haven't yet found a link to the solution or a discussion on the internal trick to make this work. In principle the view structure is: NavigationSplitView { // master list List(selection : $selectedItem { } } content: { TextEditor(text: $selectedItem.text) // works // or CustomTextView(text: $selectedItem.text) // all examples I've found so far fail to properly display changes to the text when edited } My current thought is that the internal Coordinator needs to know that there has been a selection change so you can synchronise the significant change in the contents of the text binding. Again TextEditor doesn't need to know that. makeNSView is only called once, so there isn't any regeneration of the NSTextView that you could rely on. Have tried on both macOS and iOS and see the same results.
Posted
by purple.
Last updated
.
Post not yet marked as solved
1 Replies
102 Views
Hello everyone,I am a student who is working on my final project of my college.I do not get an official development account since I do not need to put my app on AppStore. In my project,I need to use the camera of iOS device, and I know I need to add NSCameraUsageDesciption in Info.plist.However, as I add the description in my Info and build my project, it failed and says"Provisioning profile "iOS Team Provisioning Profile: " doesn't include the NSCameraUsageDescription and NSPhotoLibraryUsageDescription entitlements." I also notice that in the Info.plist file, when I change the property type to entitlements,I just cannot find NSCameraUsageDescription when I add row. What's the problem?Is this because I am not an official developer?
Posted Last updated
.
Post not yet marked as solved
0 Replies
99 Views
If put a List in ScrollVIew, List won't appear: import SwiftUI struct BugView: View { let numbers: [Int] = [0, 1, 2] var body: some View { ScrollView { List(numbers, id: \.self) { number in Text(number.description) } } } } #Preview { BugView() }
Posted Last updated
.
Post not yet marked as solved
0 Replies
122 Views
I have a simple example to demonstrate... struct MyView: View { var body: some View { Text("WOW") } } struct MyOtherView: View { var body: some View { NavigationStack { Text("WOW") } } } On VisionOS, MyOtherView has a glass background effect that cannot be disabled. glassBackgroundEffect(displayMode: .never) .background(.clear), .foregroundColor(.clear), none of them work. I then resorted to the SwiftUIIntrospect package to try set .clear on various child objects of the NavigationStack but nothing is working. I am in control of my own glass containers. I have a couple with space between them, but with the NavigationStack it sets a background behind both of them ruining the effect. This is what MyOtherView renders as: I'm looking for it to be completely transparent except the text. Like the below layout. For now I will have to roll my own navigation.
Posted
by lbennett.
Last updated
.
Post not yet marked as solved
0 Replies
56 Views
When you run the following SwiftUI code, images unrelated to animation will flicker. import SwiftUI struct TestAnimationView: View { @State private var effectFlg = false private let imageName = "image1" @State var rotationDegrees = 0.0 var body: some View { VStack() { Text("Rectangle") Rectangle() .foregroundColor(.blue) .frame(width: 100, height: 100) .padding(.bottom, 30) Text("PNG Image") if let _imageName = Bundle.main.path(forResource: imageName, ofType: "png") { Image(uiImage: UIImage(contentsOfFile: _imageName)!) .resizable() .frame(width: 100, height: 100) .padding(.bottom, 30) } Text("PNG Image") if let _imageName = Bundle.main.path(forResource: imageName, ofType: "png") { Image(uiImage: UIImage(contentsOfFile: _imageName)!) .resizable() .frame(width: 100, height: 100) // .scaleEffect(self.effectFlg ? 1 : 0.8) .rotationEffect(.degrees(self.rotationDegrees)) } Spacer() Button("Start Animation") { withAnimation(.default.repeatForever().speed(0.5)) { if self.effectFlg { rotationDegrees = 0.0 } else { rotationDegrees = 360.0 } self.effectFlg.toggle() } } } } }
Posted
by POCO2002.
Last updated
.
Post not yet marked as solved
2 Replies
556 Views
This is my test code. import SwiftUI extension View { @MainActor func render(scale: CGFloat) -> UIImage? { let renderer = ImageRenderer(content: self) renderer.scale = scale return renderer.uiImage } } struct ContentView: View { @Environment(\.colorScheme) private var colorScheme @State private var snapImg: UIImage = UIImage() var snap: some View { Text("I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .foregroundStyle(colorScheme == .dark ? .red : .green) } @ViewBuilder func snapEx() -> some View { VStack { Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .foregroundStyle(colorScheme == .dark ? .red : .green) Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .background(.pink) Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .background(.purple) Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .foregroundStyle(colorScheme == .dark ? .red : .green) Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!") .foregroundStyle(colorScheme == .dark ? .red : .green) } } @ViewBuilder func snapView() -> some View { VStack { Text("Text") Text("Test2") .background(.green) snap snapEx() } } var body: some View { let snapView = snapView() VStack { snapView Image(uiImage: snapImg) Button("Snap") { snapImg = snapView.render(scale: UIScreen.main.scale) ?? UIImage() } } } } When using ImageRenderer, there are some problems with converting View to images. For example, Text cannot automatically modify the foreground color of Dark Mode. This is just a simple test code, not just Text. How should I solve it?
Posted
by jBanana.
Last updated
.
Post not yet marked as solved
0 Replies
96 Views
I've been trying to follow the "Supporting Continuity Camera in Your Mac App" article to implement the "Import from iPhone or iPad" menu for my MacOS app. I've been able to replicate most of the article in a test AppKit application but cannot do the same in my SwiftUI application. I'm not sure how to get the "NSMenuItemImportFromDeviceIdentifier" identifier into a SwiftUI Menu or create a NSMenu with a NSMenuItem for a SwiftUI app. I'm also not sure how to handle receiving the image in the SwiftUI environment. Any advice you might have is appreciated. Thanks!
Posted Last updated
.