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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

iOS app running in compatibility mode on Apple Vision Pro does not apply hoverEffect to SwiftUI View
We tested our iOS app on visionOS and found that the hover effect works on most of UIKit views, but it does not work on most of SwiftUI views. SwiftUI views are used within UIHostingController. I created a new project (Storyboard based iOS app) and displayed the following SwiftUI view in UIHostingController and found that the buttons in the List were highlighted, but not the standalone buttons. struct SwiftUIView: View { var body: some View { List { // This button has the hover effect. Button { print("Hello") } label: { Text("Hello") } } // This button does't have the hover effect. Button { print("Hello") } label: { Text("Hello") } .hoverEffect() } } Is there a way to highlight any SwiftUI view?
2
1
329
Jun ’24
SwiftUI, REST, and websockets
I'm coming back to iOS development after years away and diving head-first into SwiftUI. It's a lot of fun, but I've hit a brick wall. The scenario is I have a main view (which itself is a tabview, not important other than that it's not the top-level of the view hierarchy). This has subviews that rely on data coming back from a REST call to the cloud, but then some subviews need to turn around and make subsequent network calls to set up websockets for realtime updates. In the main view's .onAppear, I fire off an async REST call, it returns JSON that gets parsed into a ModelView. The ViewModel is declared in the top view like this: class ViewModel: ObservableObject { @Published var appData = CurrentREST() // Codables from JSON @State var dataIsLoaded : Bool = false func fetchData() async { await _ = WebService().downloadData(fromURL: "current") { currentData in DispatchQueue.main.async { self.appData = currentData self.dataIsLoaded = true } } } } The main view declares the model view: struct HomeTabView: View { @ObservedObject var viewModel = ViewModel() @Binding private var dataReceived: Bool ... } In the toplevel view, the REST call is triggered like this: .onAppear { if !viewModel.dataIsLoaded { Task { await viewModel.fetchData() DispatchQueue.main.async { self.dataReceived = true } } } } The viewModel gets passed down to subviews so they can update themselves with the returned data. That part all works fine. But it's the next step that break down. A subview needs to go back to the server and set up subscriptions to websockets, so it can do realtime updates from then on. It's this second step that is failing. The dataReceived binding is set to true when the REST call has completed. The viewModel and dataReceived flags are passed down to the subviews: SummaryView(viewModel: viewModel, dataIsLoaded: self.dataReceived) What needs to happen next is inside the subview to call a function to wire up the next websocket steps. I've tried setting up: struct SummaryView: View { @ObservedObject var viewModel: ViewModel @State var dataIsLoaded: Bool = false ... }.onChange(of: dataIsLoaded) { setupWebSocket() } Problem is, the onChange never gets called. I've tried various permutations of setting up a @State and a @Binding on the view model, and a separate @State on the main view. None of them get called and the subview's function that wires up the websockets never gets called. The basic question is: How do you trigger a cascading series of events through SwiftUI so external events (a network call) can cascade down to subviews and from there, their own series of events to do certain things. I haven't gone deep into Combine yet, so if that's the solution, I'll go there. But I thought I'd ask and see if there was a simpler solution. Any suggestions or pointers to best practices/code are most appreciated.
3
0
208
3w
SwiftUI: listSectionSeparator not working on macOS
Hi, When I use 'listSectionSeparator' on hide the section separator on a List 'section', it works as expected on iOS, but doesn't have any effect on macOS. Is that a known issue? Are there any workarounds for this? Here's a basic reproducible example: import SwiftUI struct TestItem: Identifiable, Hashable { let id = UUID() let itemValue: Int var itemString: String { get { return "test \(itemValue)" } } } struct TestListSelection: View { let testArray = [TestItem(itemValue: 1), TestItem(itemValue: 2), TestItem(itemValue: 3), TestItem(itemValue: 4)] @State private var selectedItem: TestItem? = nil var body: some View { List (selection: $selectedItem) { Section("Header") { ForEach (testArray, id: \.self) { item in Button { print("main row tapped for \(item.itemValue)") } label: { HStack { Text(item.itemString) Spacer() Button("Tap me") { print("button tapped") } .buttonStyle(.borderless) } } .buttonStyle(.plain) } } .listSectionSeparator(.hidden) // has no effect on macOS Section("2nd Header") { ForEach (testArray, id: \.self) { item in Text(item.itemString) } } .listSectionSeparator(.hidden) // has no effect on macOS } .listStyle(.plain) } } #Preview { TestListSelection() }
0
1
130
3w
UIVisualEffectView isn't blurred during the device rotation
Hey everyone, I’m facing a bug when using UIVisualEffectView in a SwiftUI context via UIViewRepresentable. When the SwiftUI view modifier .blur(radius: xx, opaque: true) is applied to it during rotation, the blur effect isn’t applied. Instead, the view becomes completely white or black, depending on the UIBlurEffect.Style applied to the UIVisualEffectView. I’m not sure how to proceed with this issue and am seeking your help. Below is a simple, reproducible piece of code: import SwiftUI struct ContentView: View { var body: some View { ZStack { Circle() .fill(.pink) GlassBackgroundView() .blur(radius: 7, opaque: true) } .ignoresSafeArea() } } #Preview { ContentView() } private struct GlassBackgroundView: UIViewRepresentable { func makeUIView(context: Context) -> UIVisualEffectView { UIVisualEffectView(effect: UIBlurEffect(style: .regular)) } func updateUIView(_ uiView: UIVisualEffectView, context: Context) { } }
0
0
143
3w
How to support foregroundColor (deprecated) and foregroundStyle in watchOS 9/10?
In my Watch app on watchOS 9 I was using .foregroundColor(myColour) to colour the text in a widgetLabel on a corner complication like this: let myColour: Color = functionThatReturnsAColorObjectConstructedLike Color.init(...) // green .widgetLabel { Text(myText) .foregroundColor(myColour) } It worked fine; the widget label was green. Now, in watchOS 10, I see that foregroundColor() is being deprecated in favour of foregroundStyle(), and I can use .foregroundStyle(.green), and - importantly - foregroundStyle() is only available on watchOS 10 and newer. myColour is calculated depending on some other info, so I can't just write .green, and when I use .foregroundStyle(myColour) the widget label comes out as white every time, even if I set myColour = .green. I think I have to use some sort of extension to pick the right combination, something like: extension View { func foregroundType(colour: Colour, style: any ShapeStyle) -> some THING? { if #available(watchOS 10.0, *) { return foregroundStyle(style) } else { return foregroundColor(colour) } } } // Usage let myStyle: any ShapeStyle = SOMETHING? ... .widgetLabel { Text(myText) .foregroundType(colour: myColour, style: myStyle) It doesn't work. I just can't figure out what should be returned, nor how to return it. Any ideas?
2
2
1.6k
Sep ’23
MapKit mapItemDetailAccessory Custom View
Hi all, It wasn't extensively covered in the "Unlock the power of places with MapKit" at WWDC, but is it possible to add your own views to the mapItemDetailAccessory? The default view is great, but I would like to add a button for opening a new window showing another view. The documentation is rather limited at the moment so I thought I would ask here. Thanks in advance.
0
0
163
3w
Xcode 15 beta 7 Previews building issue
Summary When trying to display SwiftUI previews, building the previews may fail with the following error: Linking failed: linker command failed with exit code 1 (use -v to see invocation) ld: warning: search path '/Applications/Xcode.app/Contents/SharedFrameworks-iphonesimulator' not found ld: warning: Could not find or use auto-linked framework 'CoreAudioTypes': framework 'CoreAudioTypes' not found Note that may app does not use CoreAudioTypes. Observation This issue seems to occur when two conditions are met: The SwiftUI view must be located in a Swift Package Somewhere in either the View or the #Preview a type from another package has to be used. Say I have to packages one named Model-package and one named UI-Package. The UI-Package depends on the Model-Package. If I have a SwiftUI view in the UI-Package that uses a type of the Model-Package either in the View itself or in the #Preview, then the described error occurs. If I have a View in the UI-package that does not use a type of the Model-Package anywhere in its View or #Preview then the SwiftUI Preview builds and renders successful. I created a bug report: FB13033812
35
10
23k
Aug ’23
LinkDylibError when previewing SwiftUI view from a package.
I have two (local) Swift packages (both with a single library product): RemoteImage, which defines setImage(from:) function on UIImageView and SatelitUI package which directly depends on the first one and defines some views. But when I'm trying to preview views from the second package I'm getting the following error: linker command failed with exit code 1 (use -v to see invocation) LinkDylibError: Failed to build TrailerView.swift Linking failed: linker command failed with exit code 1 (use -v to see invocation) ld: warning: directory not found for option '-F/Applications/Xcode-beta.app/Contents/SharedFrameworks-iphonesimulator' Undefined symbols for architecture x86_64:   "(extension in RemoteImage):__C.UIImageView.setImage(from: Foundation.URL?) -> ()", referenced from:       (extension in SatelitUI_PreviewReplacement_TrailerView_2):SatelitUI.TrailerView.(previewupdate in _8C3731B0EF007627509BEEB93277D681)(with: SatelitUI.Trailer?) -> () in TrailerView.2.preview-thunk.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Apparently, Xcode fails to link the library from the first package because it's dynamic. Static linking works as expected. It's a bug I believe?
2
1
1.4k
Jun ’20
How to embed SwiftData model container in a custom file package document type
Hi all, I have done a lot of research on this but am not able to come up with a workable solution. Background: I am trying to make an universal app on macOS/iOS that organizes media (image/video/pdf); think of its functionality like Apple's Photos app. So for my app document type, I would have my custom file package and within the package folder, there would be a SwiftData model container file and folders to hold user media. Approaches taken: DocumentGroup with SwiftData model then write directly into the file package In my App scene, I create document by having DocumentGroup(editing: .customDocument, migrationPlan: CustomMigrationPlan.self). This will create a document with a model container with my SwiftData model. And when I need to add media files into the document, I get the URL of the document, then use FileManager to write the file into the desired folder in the document. The result is that the media file is saved in the file package but then the SwiftData container is corrupted (all model data is reset to empty.) I am now trying to: 2. DocumentGroup with custom file package then try to embed SwiftData container In my current approach, I would create a document by having DocumentGroup(newDocument: CustomFileDocument()). I have custom FileDocument and FileWrapper. But the problem is I don't know how to embed a SwiftData container into my FileDocument. Is it possible to create a SwiftData model container when my FilerWrapper initialize? I can't figure out how to do this. Can anyone please advice on how I should accomplish this? Or if maybe I am looking at this problem wrongly? Do I need to use AppKit/UIKit with Core Data because it's currently not possible with SwiftUI/SwiftData? Thank you so much for reading and any input is greatly appreciated.
0
0
173
3w
TipKit vs. Swift 6 + Concurrency
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1. The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit): struct ParameterRuleTip: Tip { // Define the app state you want to track. @Parameter static var isLoggedIn: Bool = false Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state. Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this. The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
6
2
397
Jun ’24
SwiftUI List selection bug
Is there a way to optimize a List in SwiftUI? There is a problem with selection not working properly when the List has many rows. If you scroll to multi-select and up, some rows in the middle are not selected. I have an issue where selecting an unselected row deselects nearby rows. Is there any way for selection to work reliably even for a List of many rows? I would like to find a solution that is stable even when multiple lines are selected, like mail and note, which are the default apps in ios. ps. I am using CoreData. @State var selectedItem = Set<MyEntity>() List(selection: $selectItem){   ForEach(items, id: \.self){ item in     ContactsRow(contactsData: item)   } } .environment(\.editMode, $editMode)
1
0
1.3k
Jun ’22
QuickLook sheet not opening in iOS
I'm developing an application in which saving files and opening them with .quickLookis in important role. However, after putting my application to TestFlight and letting a friend of mine test it with his phone (iOS 17.4.1, iPhone 15 Pro) it appears that sometimes when opening a file the QuickLook sheet doesn't open until the app's focus is lost. @State Button("Open file") { url = someFileUrl }.quickLookPreview($url)
2
0
143
3w
SwiftUI iOS 17 White screen when I return back with Navigation Stack
When using the Navigation Stack with paths, I've faced an issue where tapping the 'back' button on the custom navigation bar results in a blank screen. With light theme the screen is white, when using dark theme the screen is black. I've found a decision with using an environment value to dismiss a single screen when needed. However, the problem becomes more prominent when I want to pop back to the root view. This issue has become since updating to iOS 17.
2
3
1.1k
Oct ’23
navigationDestination + NavigationPath broken on iOS 17
Using the new navigationDestination and NavigationPath functions previously on iOS 16 everything has been working fine using a custom back button, which calls path.removeLast(). However, if we try this on iOS 17, the screen being removed flashes white. You can try this code as an example (NOTE THE WHITE FLASH ON REMOVE LAST): struct DetailView: View { @Binding var path: NavigationPath var body: some View { ZStack { Color.black VStack(alignment: .center) { Spacer() Button(action: { path.removeLast() }, label: { Text("BACK") }) Spacer() } } } } struct ParentView: View { @State var path: NavigationPath = .init() var body: some View { NavigationStack(path: $path) { ZStack { Color.red VStack(alignment: .center) { Spacer() Button(action: { path.append("TEST") }, label: { Text("FORWARD") }) Spacer() } } .navigationDestination(for: String.self) { _ in DetailView(path: $path) } } } } Any work arounds? Suggestions?
3
2
943
Sep ’23
Is it possible to loop a ScrollView to repeat infinitely?
I have a horizontal scroll view and a fixed array. I would like to loop it such that when I scroll left and get near the end, the array will add the items in the beginning to the end so that the user can continue to scroll. I would like this to happen when scrolling both left and right and to not have the current position of the user jump around. Here is my code. What am I missing? Would appreciate any and all help. import SwiftUI import Algorithms struct ContentView: View { @State private var timePosition = ScrollPosition(idType: Int.self, edge: .leading) @State private var times: [Int] = Array(0...23) var body: some View { ScrollView(.horizontal, showsIndicators: false) { LazyHStack(spacing: 0) { ForEach(times, id:\.self) { time in Text("\(time)") .font(.system(.callout, design: .monospaced, weight: .semibold)) .padding(8) .frame(width: 180, height: 110, alignment: .topLeading) .border(width: 1, edges: [.leading, .trailing], color: .primary.opacity(0.05)) .id(time) } } .scrollTargetLayout() } .frame(height: 110) .scrollPosition($timeScrollPosition, anchor: .center) .onScrollTargetVisibilityChange(idType: Int.self) { timeIDs in if let currentViewID = model.timeScrollPosition.viewID { if timeIDs.contains(times[times.count - 2]) { times.rotate(toStartAt: times.count - 1) } if timeIDs.contains(times[1]) { times.rotate(toStartAt: times.count-1) } print("New times: \(times)") timeScrollPosition.scrollTo(id: currentViewID) } } } }
0
0
135
3w
Obscuration of Specific Content in Screenshots on visionOS
Hello, I am currently developing an app using visionOS, and I am looking for a way to obscure specific content in screenshots. My app includes certain content that is exclusive to premium users, and I need to hide these parts when screenshots are shared on social media. In iOS, I was able to achieve this by extending SecureField to hide specific Views or Images, but this method does not work in visionOS. I am seeking advice on the best approach to implement this feature in visionOS. https://github.com/yoxisem544/ScreenshotPreventing-iOS Specifically, I would appreciate guidance on the following points: The optimal method for obscuring specific Views or Images in screenshots on visionOS Any tips or tricks when using existing components similar to SecureField Techniques or approaches used by other developers to implement similar features Your assistance would be greatly appreciated. Thank you for your help.
0
0
139
3w
SwiftUI SideMenu Navigation Issue
I am currently refactoring my app's side menu to be more like Twitter's. I have the UI down in terms of how the side menu looks and appears, but the issue is navigating to a view from the side menu. The views that a user can go to from the side menu are a mix of SwiftUI views & UIKit View Controllers. As of right now, when a user navigates to a view from the side menu, it presents it modally as a sheet. I want it to have regular navigation, where the user goes to the view displayed in full screen and can tap on the back button to go back to the previous view. Here is the associated code: SideMenuView.swift SideMenuViewModel.swift How can I modify the navigation logic to be like Twitter's? I've been stuck for days trying to find a fix but it has been a struggle.
1
0
214
3w
Pop to root view when selected tab is tapped again for WebKit
Hello everyone! I have a WKWebView in my swiftui app and would like to enable to "pop root view when selected tab is tapped again" feature, but I have been unable to figure out how to implement this. Here's the basic code: class TabIdentifierModel:ObservableObject { @Published var tabSelection:TabIdentifier { willSet { if newValue == tabSelection { NotificationCenter.default.post(name: .popRootView, object: nil, userInfo: ["tab": newValue.rawValue]) } } } init() { tabSelection = .home } } struct ContentView: View { @AppStorage(AppStorageKeys.enableShorts) var enableShorts = true @StateObject var storeVM = StoreVM() @StateObject var downloadURLManager = DownloadURLManager.shared @State var downloadViewIsOpen = false // ...... @State var tabSelection = TabIdentifierModel() var body: some View { TabView(selection: $tabSelection.tabSelection) { // ...... WebViewWrapper(url: $libraryTabURL) .tabItem { Label { Text("Library") } icon: { Image(systemName: "folder.fill") } }.tag(TabIdentifier.library) // ...... } .environmentObject(tabSelection) } } Tapping on the tab again doesn't seem to set the value again thus the NotificationCenter.default.post is not sent and the web view is not reloaded. Help would be much appreciated! Thanks in advance!
0
0
150
3w