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

Can I preview "regular" view in widget extension?
Basically, in my widget/live activity, I want to extract reusable views into a separate file with an isolated view and preview. Dummy example below. I cannot do it because it says "missing previewcontext". The only way I've found is to add the view to my main app target, but I don't want to clutter my main app wiews that only exist in my widgets if I can avoid it. Can this be done somehow? Thoughts appreciated. Dummy example (tried with and without "previewLayout": struct StatusActivityView: View { let status: UserStatusData var body: some View { VStack(alignment: .center) { Text("Dummy example") }.background(.blue).padding(5) } } @available(iOS 16.2, *) struct StatusActivityView_Previews: PreviewProvider { static var previews: some View { let status = WidgetConstants.defaultEntry() return StatusActivityView(status: status).previewLayout(.sizeThatFits) } }
2
0
75
3d
iOS DisclosureGroup content clipping
I have a SwiftUI page that I want to simplify by showing basic information by default, and putting the additional info behind a "Details" DisclosureGroup for advanced users. I started by laying out all the components and breaking things into individual Views. These all are laid out and look fine. Then I took several of them and added them inside a DisclosureGroupView. But all of a sudden, the views inside started getting crunched together and the contents of the DisclosureGroup got clipped about 2/3 of the way down the page. The problem I'm trying to solve is how to show everything inside the DIsclosureGroup. The top-level View looks like this: VStack { FirstItemView() SecondView() DetailView() // <- Shows disclosure arrow } Where DetailView is: struct DetailView: View { @State var isExpanded = true var body: some View { GeometryReader { geometry in DisclosureGroup("Details", isExpanded: $isExpanded) { ThirdRowView() Spacer() FourthRowView() VStack { FifthRowWithChartView() CaptionLabelView(label: "Third", iconName: "chart.bar.xaxis") } } } } } The FifthRowWithChartView is half-clipped. One thing that might contribute is that there is a Chart view at the bottom of this page. I've tried setting the width and height of the DisclosureGroup based on the height returned by the GeometryReader, but that didn't do anything. This is all on iOS 17.6, testing on an iPhone 15ProMax. Any tips or tricks are most appreciated.
2
0
94
3d
How to animate NavigationSplitView's detailView column.
Having a traditional 'NavigationSplitView' setup, I am looking for a way to animate it the same as the sidebarView, where there is a button to toggle and it animates by sliding out from the right side of the view, however the closest I have gotten was manipulating the 'navigationSplitViewColumnWidth' but that always results in the view instantly appearing / disappearing. I am using SwiftUI for a MacOS specific app. Here is just a general idea of what I am currently doing, it is by no means a reflection of my real code but serves the purpose of this example. struct ContentView: View { @State private var columnWidth: CGFloat = 300 var body: some View { NavigationSplitView { List { NavigationLink(destination: DetailView(item: "Item 1")) { Text("Item 1") } NavigationLink(destination: DetailView(item: "Item 2")) { Text("Item 2") } NavigationLink(destination: DetailView(item: "Item 3")) { Text("Item 3") } } .navigationTitle("Items") } detail: { VStack { DetailView(item: "Select an item") Button(action: toggleColumnWidth) { Text(columnWidth == 300 ? "Collapse" : "Expand") } .padding() } } .navigationSplitViewColumnWidth(columnWidth) } private func toggleColumnWidth() { withAnimation { columnWidth = columnWidth == 300 ? 0 : 300 } } } struct DetailView: View { var item: String var body: some View { Text("Detail view for \(item)") .navigationTitle(item) .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
1
0
168
3d
macOS SwiftUI Sheets are no longer resizable (Xcode 16 beta2)
For whatever reason SwiftUI sheets don't seem to be resizable anymore. The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2. Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
4
1
109
3d
Tokenised text search in SwiftData help
The SwiftData predicate documentation says that it supports the contains(where:) sequence operation in addition to the contains(_:) string comparison but when I put them together in a predicate to try and perform a tokenised search I get a runtime error. Unsupported subquery collection expression type (NSInvalidArgumentException) I need to be able to search for items that contain at least one of the search tokens, this functionality is critical to my app. Any suggestions are appreciated. Also does anyone with experience with CoreData know if this is possible to do in CoreData with NSPredicate? import SwiftData @Model final class Item { var textString: String = "" init() {} } func search(tokens: Set<String>, context: ModelContext) throws -> [Item] { let predicate: Predicate<Item> = #Predicate { item in tokens.contains { token in item.textString.contains(token) } } let descriptor = FetchDescriptor(predicate: predicate) return try context.fetch(descriptor) }
2
1
138
2d
Inconsistency on view lifecycle events between UIKit and SwiftUI when using UIVPageViewController
Overview I've found inconsistency on view lifecycle events between UIKit and SwiftUI as the following shows when using UIVPageViewController and UIHostingController as one of its pages. SwiftUI View onAppear is only called at the first time to display and never called in the other cases. UIViewController viewDidAppear is not called at the first time to display, but it's called when the page view controller changes its page displayed. The whole view structure is as follows: UIViewController (root) UIPageViewController (as its container view) UIHostingController (as its page) SwiftUI View (as its content view) UIViewControllerRepresentable (as a part of its body) UIViewController (as its content) Environment Xcode Version 15.4 (15F31d) iPhone 15 Pro (iOS 17.5) (Simulator) iPhone 8 (iOS 15.0) (Simulator) Sample code import UIKit import SwiftUI class ViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { private var pageViewController: UIPageViewController! private var viewControllers: [UIViewController] = [] override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { pageViewController.delegate = self pageViewController.dataSource = self let page1 = UIHostingController(rootView: MainPageView()) let page2 = UIViewController() page2.view.backgroundColor = .systemBlue let page3 = UIViewController() page3.view.backgroundColor = .systemGreen viewControllers = [page1, page2, page3] pageViewController.setViewControllers([page1], direction: .forward, animated: false) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard let pageViewController = segue.destination as? UIPageViewController else { return } self.pageViewController = pageViewController } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { print("debug: \(#function)") } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { print("debug: \(#function)") guard let viewControllerIndex = viewControllers.firstIndex(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0, viewControllers.count > previousIndex else { return nil } return viewControllers[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { print("debug: \(#function)") guard let viewControllerIndex = viewControllers.firstIndex(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 guard viewControllers.count != nextIndex, viewControllers.count > nextIndex else { return nil } return viewControllers[nextIndex] } } struct MainPageView: View { var body: some View { VStack(spacing: 0) { PageContentView() PageFooterView() } .onAppear { print("debug: \(type(of: Self.self)) onAppear") } .onDisappear { print("debug: \(type(of: Self.self)) onDisappear") } } } struct PageFooterView: View { var body: some View { Text("PageFooterView") .padding() .frame(maxWidth: .infinity) .background(Color.blue) .onAppear { print("debug: \(type(of: Self.self)) onAppear") } .onDisappear { print("debug: \(type(of: Self.self)) onDisappear") } } } struct PageContentView: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> some UIViewController { PageContentViewController() } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {} } class PageContentViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { view.backgroundColor = .systemYellow let label = UILabel() label.text = "PageContentViewController" label.font = .preferredFont(forTextStyle: .title1) view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("debug: \(type(of: Self.self)) \(#function)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("debug: \(type(of: Self.self)) \(#function)") } } Logs // Display the views debug: MainPageView.Type onAppear debug: PageFooterView.Type onAppear // Swipe to the next page debug: pageViewController(_:viewControllerAfter:) debug: pageViewController(_:viewControllerBefore:) debug: PageContentViewController.Type viewDidDisappear(_:) debug: pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) debug: pageViewController(_:viewControllerAfter:) // Swipe to the previous page debug: PageContentViewController.Type viewDidAppear(_:) debug: pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) debug: pageViewController(_:viewControllerBefore:) As you can see here, onAppear is only called at the first time to display but never called in the other cases while viewDidAppear is the other way around.
0
0
78
5d
Disable reverb effect in immersive spaces
I'm developing an app where a user can bring a video or content from a WKWebView into an immersive space using SwiftUI attachments on a RealityView. This works just fine, but I'm having some trouble configuring how the audio from the web content should sound in an immersive space. When in windowed mode, content playing sounds just fine and very natural. The spatial audio effect with head tracking is pronounced and adds depth to content with multichannel or Dolby Atmos audio. When I move the same web view into an immersive space however, the audio becomes excessively echoey, as if a large amount of reverb has been put onto the audio. The spatial audio effect is also decreased, and while still there, is no where near as immersive. I've tried the following: Setting all entities in my space to use channel audio, including the web view attachment. for entity in content.entities { entity.channelAudio = ChannelAudioComponent() entity.ambientAudio = nil entity.spatialAudio = nil } Changing the AVAudioSessionSpatialExperience: And I've also tried every soundstage size and anchoring strategy, large works the best, but doesn't remove that reverb. let experience = AVAudioSessionSpatialExperience.headTracked( soundStageSize: .large, anchoringStrategy: .automatic ) try? AVAudioSession.sharedInstance().setIntendedSpatialExperience(experience) I'm also aware of ReverbComponent in visionOS 2 (which I haven't updated to just yet), but ideally I need a way to configure this for visionOS 1 users too. Am I missing something? Surely there's a way for developers to stop the system messing with the audio and applying these effects? A few of my users have complained that the audio sounds considerably worse in my cinema immersive space compared to in a window.
2
0
186
3d
What is the info property of SwiftUI::Layer
What is the info property of SwiftUI::Layer? I couldn't find any document or resource about it. It appears in SwiftUI::Layer's definition: struct Layer { metal::texture2d<half> tex; float2 info[5]; /// Samples the layer at `p`, in user-space coordinates, /// interpolating linearly between pixel values. Returns an RGBA /// pixel value, with color components premultipled by alpha (i.e. /// [R*A, G*A, B*A, A]), in the layer's working color space. half4 sample(float2 p) const { p = metal::fma(p.x, info[0], metal::fma(p.y, info[1], info[2])); p = metal::clamp(p, info[3], info[4]); return tex.sample(metal::sampler(metal::filter::linear), p); } };
0
1
164
6d
TabSection always show sections actions.
I'm giving a go to the new TabSection with iOS 18 but I'm facing an issue with sections actions. I have the following section inside a TabView: TabSection { ForEach(accounts) { account in Tab(account.name , systemImage: account.icon, value: SelectedTab.accounts(account: account)) { Text(account.name) } } } header: { Text("Accounts") } .sectionActions { AccountsTabSectionAddAccount() } I'm showing a Tab for each account and an action to create new accounts. The issue I'm facing is that when there are no accounts the entire section doesn't appear in the side bar including the action to create new accounts. To make matters worse the action doesn't show at all in macOS even when there are already accounts and the section is present in side bar. Is there some way to make the section actions always visible?
0
0
127
6d
UI Tab Bar
Anyone else get these warnings when using UI Tab Bar in visionOS? Are these detrimental to pushing my visionOS app to the App Review Team? import SwiftUI import UIKit struct HomeScreenWrapper: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> UITabBarController { let tabBarController = UITabBarController() // Home View Controller let homeVC = UIHostingController(rootView: HomeScreen()) homeVC.tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: "house"), tag: 0) // Brands View Controller let brandsVC = UIHostingController(rootView: BrandSelection()) brandsVC.tabBarItem = UITabBarItem(title: "Brands", image: UIImage(systemName: "bag"), tag: 1) tabBarController.viewControllers = [homeVC, brandsVC] return tabBarController } func updateUIViewController(_ uiViewController: UITabBarController, context: Context) { // Update the UI if needed } } struct HomeScreenWrapper_Previews: PreviewProvider { static var previews: some View { HomeScreenWrapper() } }
1
0
121
4d
iOS18 beta2 NavigationStack: Tapping Back from a lower-level View returns to the Root View / No transition animation
This is a report of an issue that appears to be a regression regarding NavigationStack. While investigating another issue [iOS18 beta2: NavigationStack, Views Being Popped Automatically] , I encountered this separate issue and wanted to share it. In a NavigationStack with three levels: RootView - ContentView - SubView, tapping the Back button from the SubView returned to the RootView instead of the ContentView. This issue is similar to one that I previously posted regarding iOS16.0 beta. https://developer.apple.com/forums/thread/715970 Additionally, there is no transition animation when moving from ContentView to SubView. The reproduction code is as follows: import SwiftUI struct RootView2: View { @State var kind: Kind = .a @State var vals: [Selection] = { return (1...5).map { Selection(num: $0) } }() @State var selection: Selection? var body: some View { if #available(iOS 16.0, *) { NavigationStack { NavigationLink { ContentView2(vals: $vals, selection: $selection) } label: { Text("album") } .navigationDestination(isPresented: .init(get: { return selection != nil }, set: { newValue in if !newValue { selection = nil } }), destination: { if let selection { SubView2(kind: .a, selection: selection) } }) } } else { EmptyView() } } } struct ContentView2: View { @Binding var vals: [Selection] @Binding var selection: Selection? @Environment(\.dismiss) private var dismiss var body: some View { list .onChange(of: self.selection) { newValue in print("changed: \(String(describing: newValue?.num))") } } @ViewBuilder private var list: some View { if #available(iOS 16.0, *) { List(selection: $selection) { ForEach(self.vals) { val in NavigationLink(value: val) { Text("\(String(describing: val))") } } } } } } // struct SubView2: View { let kind: Kind let selection: Selection var body: some View { Text("Content. \(kind): \(selection)") } }
5
0
138
3d
Question About Weak Self Usage
Hello everyone. I have a small question about Weak Self. In the example below, I am doing a long process to the data I query with SwiftData. (For this reason, I do it in the background.) I don't know if there is a possibility of a memory leak when the view is closed because this process takes a long time. import SwiftUI import SwiftData struct ActiveRegView: View { @Query(filter: #Predicate<Registration> { $0.activeRegistration }, animation: .default) private var regs: [Registration] @Environment(ViewModel.self) private var vm @State private var totalParkingFee: Decimal = 0 var body: some View { ... .onAppear { var totalParkingFee = Decimal() DispatchQueue.global(qos: .userInitiated).async { for reg in regs { totalParkingFee += vm.parkingFee(from: reg.entryRegistration.entryDate, to: .now, category: reg.category, isCustomPrice: reg.isCustomPrice) } DispatchQueue.main.async { withAnimation { totalParkingFee = totalParkingFee } } } } } } I use ViewModel with @Environment, so I don't initilize ViewModel every time view is initilized. I know it's a simple question and I thank you in advance for your answers.
0
0
74
6d
Xcode Accessibility audit in UI Tests gives less than stellar results
I have added a UI test that uses the newish app.performAccessibilityAudit() on each of the screens in my SwiftUI app. I get a handful of test failures for various accessibility issues. Some of them are related to iOS issues (like the "legal" button in a map view doesn't have a big enough tappable are; and, I think, there is a contrast issue with selected tabs in a tab bar, or maybe it is a false positive). Two of the error type I get are around Text elements that use default font styles (like headline) but that apparently get clipped at times and apparently "Dynamic Type font sizes are unsupported". For some of the errors it supplies a screenshot of the whole screen along with an image of the element that is triggering the error. For these text errors it only provides the overall image. After looking at the video I saw that part of the test runs the text size all the way up and I could see that at the largest size or two the text was getting cut off despite using default settings for the frames on all the Text elements. After a bit of trial and error I managed to get the text to wrap properly even at the largest of sizes and most of the related errors went away running on an iPhone simulator. I switched to an iPad simulator and the errors re-appeared even though the video doesn't show the text getting clipped. Does anyone have any tips for actually fixing these issues? Or am I in false positive land here? Also, is there any way to get more specific info out of the test failures? Looking at the entire screen and trying to guess where the issue is kinda sucks.
0
2
264
1w
Automatic Grammar Agreement with formatted number: use integer value to switch categories
Hello, I want to use Automatic Grammar Agreement to localise a string in my app, let say "three remaining activities". The string "three" is obtained by using a NumberFormatter with a numberStyle set to .spellOut (so I'm not using an Integer) var formatter: NumberFormatter = NumberFormatter() formatter.numberStyle = .spellOut let formattedCount: String = numberFormatter.string(from: count as NSNumber)! Text("key_with_string_\(formattedCount)") In my string catalog, I have translated the key key_with_string_%@ like this ^[%@ remaining activity](inflect: true), but it does not work. I've tried to add the integer value used by the number formatter in the key key_with_string_%@_%lld but it does not work. Should Automatic Grammar Agreement work normally just by using the formatted string provided by the NumberFormatter? If not, is there a way to specify to use a secondary variable (my count integer) to switch between different categories like one and other automatically? Thanks ! Axel
1
0
124
1w
Draggable Views with Child Drop Destination Elements not Draggable in iOS 18
I'm creating an app that has a number of draggable views, and each of these views themselves contain child dropDestination views. In iOS 17.x they are draggable as expected. However, in iOS 18 betas 1 & 2 a long press on these views does NOT pick them up (start the drag operation). I have not tested with macOS 15 betas but the issue may well exist there also. Is this a bug in iOS 18 betas 1 & 2 or does the implementation need to be updated somehow for iOS 18? Please see example code below: Views: import SwiftUI extension View { func dropTarget<T>(for payloadType: T.Type, withTitle title: String) -> some View where T: Transferable { modifier(DropTargetViewModifer<T>(title: title)) } } struct DropTargetViewModifer<T>: ViewModifier where T: Transferable { let title: String func body(content: Content) -> some View { content .dropDestination(for: T.self) { items, location in print("Item(s) dropped in \(title)") return true } isTargeted: { targted in if targted { print("\(title) targeted") } } } } struct InnerTestView: View { let title: String let borderColor: Color var body: some View { ZStack { Text(title) .padding() Rectangle() .stroke(borderColor) } .contentShape(Rectangle()) } } struct TestView: View { var body: some View { VStack(spacing: 0.0) { HStack(alignment: .top, spacing: 0.0) { InnerTestView(title: "Drop Zone 1", borderColor: .pink) .dropTarget(for: ItemType1.self, withTitle: "Drop Zone 1") InnerTestView(title: "Drop Zone 2", borderColor: .indigo) .dropTarget(for: ItemType2.self, withTitle: "Drop Zone 2") } InnerTestView(title: "Drop Zone 3", borderColor: .orange) .dropTarget(for: ItemType3.self, withTitle: "Drop Zone 3") } .contentShape(Rectangle()) .draggable(ItemType1(id: "Object 1")) } } struct ContentView: View { var body: some View { ScrollView { LazyVStack { TestView() TestView() InnerTestView(title: "Draggable 2", borderColor: .orange) .draggable(ItemType2(id: "Object 2")) InnerTestView(title: "Draggable 3", borderColor: .indigo) .draggable(ItemType3(id: "Object 3")) } .padding() } } } Transfer Representations: import UniformTypeIdentifiers import CoreTransferable extension UTType { static let itemType1 = UTType(exportedAs: "com.droptest.typeone") static let itemType2 = UTType(exportedAs: "com.droptest.typetwo") static let itemType3 = UTType(exportedAs: "com.droptest.typethree") } struct ItemType1: Codable, Transferable { var id: String public static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .itemType1) } } struct ItemType2: Codable, Transferable { var id: String public static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .itemType2) } } struct ItemType3: Codable, Transferable { var id: String public static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .itemType3) } }
3
0
145
6d
Using availablity checks with new .defaultWindowPlacement API
How can I use availability checks with the new defaultWindowPlacement API so I can ensure visionOS 2 users get the correct window placement and visionOS 1 users fall back to the old window placement mechanism? I have tried using if #available and @available in different ways, but end up with either an error that says control flow statements aren't allowed in SceneBuilders or that the return type of the two branches of my control flow statement do not match if I omit the SceneBuilder property. An example of how to use .defaultWindowPlacement with visionOS 1 support would be nice. Thank you!
1
0
163
1w
iOS 18 Translation API availability for UIKit
After reading the documentation for TranslationSession and other API methods I got an impression that it will not be possible to use the Translation API with UI elements built with UIKit. You don’t instantiate this class directly. Instead, you obtain an instance of it by adding a translationTask(_:action:) or translationTask(source:target:action:) function to the SwiftUI view containing the content you want to translate So the main question I have to the engineers of mentioned framework is will there be any support for UIKit or app developers will have to rewrite their apps in SwiftUI just to be able to use the Translation API?
1
1
240
2d