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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

SwiftUI Document-based apps crash in iOS 18
I am trying to integrate the new iOS 18 document launching experience with my app, but opening or saving files fails with the RC version of Xcode 16. The error I receive is "Publishing changes from background threads is not allowed." I downloaded Apple's new sample code ("Writing app"), and it fails with the same error. Is there an easy fix for this?
3
0
239
2w
WKHaptic Issue when headphones are connected
Info watchOS: 11.0 (22R5348a) *Though has been present since watchOS 10. Issue: Other apps playing music cancel out WKHaptics from firing (low volume and no vibrations) Description When another app is playing music (ex: spotify) in the background while using my app, that uses WKHaptics. The WKHaptics vibrations are non existent as long as headphones are connected. When the headphones are disconnected the vibrations return. Test MVP test app >> https://github.com/mazefest/AppleCodeSupportTestApp
1
0
214
3w
setNeedsUpdateOfSupportedInterfaceOrientations changed behavior iOS 18
I'm using setNeedsUpdateOfSupportedInterfaceOrientations to force the rotation in a specific view in my app, only this view should be in landscape and the rest of the app should always be in portrait. After updating to iOS 18 and Xcode 16 RC, the behavior changed. Now after rotating occurs, my whole view seems to be rendered again, and this is resetting some states that were changed prior to rotating. This is working as expected in iOS 17 and under, and there was no change in the code in our side. The (pseudo)code below shows how I'm doing it: class NewAppDelegate: UIResponder, UIApplicationDelegate { private(set) static var instance: NewAppDelegate? var orientationLock = UIInterfaceOrientationMask.portrait func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { NewAppDelegate.instance = self return true } func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { self.orientationLock } } static func lockOrientation(_ orientation: UIInterfaceOrientationMask) { NewAppDelegate.instance?.orientationLock = orientation } static func rotate(to orientation: UIInterfaceOrientationMask) { DispatchQueue.main.async { lockOrientation(orientation) if #available(iOS 16.0, *) { guard let viewController = UIApplication.visibleViewController else { return } viewController.setNeedsUpdateOfSupportedInterfaceOrientations() } else { var rotateOrientation: UIInterfaceOrientation switch orientation { case .landscapeLeft: rotateOrientation = .landscapeLeft case .landscapeRight, .landscape: rotateOrientation = .landscapeRight default: rotateOrientation = .portrait } UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") UINavigationController.attemptRotationToDeviceOrientation() } } } class MyViewModel: ObservableObject { @Published var state: EnumViewState init() { self.state = "First State" } func changeRotation() { self.state = "Second state" AppRotationHelper.rotate(to: .landscapeRight) // After rotating `init` gets called again and `state` goes back to `"First State"` } } struct MyView: View { @StateObject var viewModel: MyViewModel ... }
0
0
161
3w
Scroll to Top gesture doesn't work when pressed in Status Bar.
I have created a paging app With SwiftUI TabView with TabViewStyle: PageTabViewStyle. In every page there is an UICollectionView holding a list of rows. Now I have used UIViewControllerRepresentable to show the view inside TabView. It works okay, but the Scroll to top gesture doesn't work here when pressed in the iPhones StatusBar. Is it a fault of TabView or I am missing Something? It may happen because of TabViews Scroll property. In UIKIT Views We needed to disable the scrollToTop property of scrollviews (Other then the desired one) is there any public API's for SwiftUI Views in replacement for setting scrollsToTop property?
3
0
160
3w
Live Activities Random Loading Spinner
Somewhat rarely, but often enough to be a problem, our live activities will entirely lock up with a frozen progress spinner and a dimmed appearance. We cannot figure out what this spinner means nor how to avoid it as it is not documented anywhere. No logs appear in Xcode nor in Console.app. We have more frequent updates enabled and are sending an update maybe once every 2 minutes, nothing that should cause us to exceed our quota. We cannot reproduce in a debugger Can we get some guidance on how to avoid this?
3
0
243
3w
Variable for DestinationView
var body: some View { VStack { List { ForEach(starSigns) {ZodiacSign in NavigationLink(destination: ZodiacSign.DestinationView) { Text(ZodiacSign.Symbol) Text(ZodiacSign.name) } } } } } } I have this basic view which gets information from a list I created, but how do I get the destination view to work where an example of it would be AriesView(), I would like the destination to be there. Currently it comes up with an error of "Protocol 'View ' cannot conform to the protocol itself" Sorry for the complexity of this question, I was struggling to explain it. THANK YOU IN ADVANCE!!!
5
0
214
3w
SwiftUI bug using .sheet(item:) and button action not called
import SwiftUI extension Int: Identifiable { public var id: Int { return self } } struct ContentView: View { @State var shareSheet: Bool = false @State var selectedNo : Int? var body: some View { VStack { ForEach(0..<2, id: \.self, content: { rowNo in Text("world \(rowNo)") Button(action: { shareSheet.toggle() selectedNo = rowNo }) { Text("Go to world\(rowNo)") } }) } .padding() .sheet(item: $selectedNo) { row in // BUG: when replacing 'row' below with 'selectedNo' nil is passed. ShareView(message:"Hello \(row)" ) } } struct ShareView: View { let message: String var body: some View { Text(message) } } }
2
0
141
3w
Changes to the bound value update the string displayed by the text field.
Is it possible to have a TextField that validates its input on every character entered by the user so that the string displayed by the text field updates only on successful validation? The documentation on the TextField seems to suggest that this is possible by using a bound value. In my testing this is not the case. Even when validation fails, the text field always updates the string displayed. Changes to the bound value update the string displayed by the text field. Editing the text field updates the bound value, as long as the formatter can parse the text. If the format style can’t parse the input, the bound value remains unchanged. https://developer.apple.com/documentation/swiftui/textfield/init(_:value:formatter:)-9jw0i The way I understand it, in case of an error thrown by ParseStrategy/parse(_ value: String) the bound value remains unchanged. Since the bound value did not change the string displayed by the text field should not be updated. I have tried the code example used in the documentation overview of the TextField to create a sample app. @State private var nameComponents = PersonNameComponents() var body: some View { TextField( "Proper name", value: $nameComponents, format: .name(style: .medium) ) .onSubmit { validate(components: nameComponents) } .disableAutocorrection(true) .border(.secondary) Text(nameComponents.debugDescription) } The bound value doesn’t have to be a string. By using a FormatStyle, you can bind the text field to a nonstring type, using the format style to convert the typed text into an instance of the bound type. The following example uses a PersonNameComponents.FormatStyle to convert the name typed in the text field to a PersonNameComponents instance. A Text view below the text field shows the debug description string of this instance. https://developer.apple.com/documentation/swiftui/textfield
3
0
167
3w
CollectionView (Inside a SwiftUI TABView as a Page) Doesn't scroll to top when Pressed near the notch area of the device.
I have created a paging app With SwiftUI TabView with TabViewStyle: PageTabViewStyle. In every page there is an UICollectionView holding a list of rows. Now I have used UIViewControllerRepresentable to show the view inside TabView. It works okay, but the iOS default phenomenon that when a user pressed out side the safeArea on top(near the notch), the collectionview auto scrolls to top, doesn't work. Is it a fault of TabView or I am missing Something?
0
0
176
3w
PhotosPicker fail to load Collections tab on iOS 18
When using PhotosPicker in SwiftUI to let users pick a photo, it will fail to load after switching to the "Collections" tab on iOS 18. This issue doesn't occur on iOS 17. Additionally, using PHPickerViewController will still have the same issue. The code is pretty simple: struct ContentView: View { @State private var selection: PhotosPickerItem? = nil var body: some View { VStack { PhotosPicker("Pick photo", selection: $selection) } .padding() } } And I create a repo for this code: https://github.com/JuniperPhoton/PhotosPickerIssueiOS18 This issue has been reported via Feedback app, and the report ID is FB15069998. I tested in the Xcode 16 Beta 6 and iOS 18 Beta 8. However with the Xcode 16 RC and the iOS 18 RC, this issue still exists. Hoping to find out any workaround to resolve this issue. Thanks.
1
1
212
3w
SwiftUI.Stepper bug from `onIncrement` and `onDecrement`?
Ok… I'm baffled here… this is very strange. Here is a SwiftUI app: import SwiftUI @main struct StepperDemoApp: App { func onIncrement() { print(#function) } func onDecrement() { print(#function) } var body: some Scene { WindowGroup { Stepper { Text("Stepper") } onIncrement: { self.onIncrement() } onDecrement: { self.onDecrement() } } } } When I run in the app in macOS (Xcode 16.0 (16A242) and macOS 14.6.1 (23G93)), I see some weird behavior from these buttons. My experiment is tapping + + + - - -. Here is what I see printed: onIncrement() onIncrement() onIncrement() onIncrement() onDecrement() What I expected was: onIncrement() onIncrement() onIncrement() onDecrement() onDecrement() onDecrement() Why is an extra onIncrement being called? And why is one onDecrement dropping on the floor? Deploying the app to iPhone Simulator does not repro this behavior (I see the six "correct" logs from iPhone Simulator).
8
0
293
3w
how do you pass a texture to a metal shader in swiftui?
specifically using the newer colorEffect, layerEffect, etc routes. the below does not seem to work. do i have to use the old MTK stuff? import SwiftUI import MetalKit struct HoloPreview: View { let startDate = Date() @State private var noiseTexture: MTLTexture? var body: some View { TimelineView(.animation) { context in RoundedRectangle(cornerRadius: 20) .fill(Color.red) .layerEffect(ShaderLibrary.iridescentEffect( .float(startDate.timeIntervalSinceNow), .texture(noiseTexture) ), maxSampleOffset: .zero) } .onAppear { noiseTexture = loadTexture(named: "perlinNoiseMap") } } func loadTexture(named imageName: String) -> MTLTexture? { guard let device = MTLCreateSystemDefaultDevice(), let url = Bundle.main.url(forResource: imageName, withExtension: "png") else { return nil } let textureLoader = MTKTextureLoader(device: device) let texture = try? textureLoader.newTexture(URL: url, options: nil) return texture } } #Preview { HoloPreview() }
1
0
197
3w
Button Touch Not Canceled in ScrollView on Modal in SwiftUI for iOS 18
When displaying a view with a Button inside a ScrollView using the sheet modifier, if you try to close the sheet by swiping and your finger is touching the Button, the touch is not canceled. This issue occurs when building with Xcode 16 but does not occur when building with Xcode 15. Here is screen cast. https://drive.google.com/file/d/1GaOjggWxvjDY38My4JEl-URyik928iBT/view?usp=sharing Code struct ContentView: View { @State var isModalPresented: Bool = false var body: some View { ScrollView { Button { debugPrint("Hello") isModalPresented.toggle() } label: { Text("Hello") .frame(height: 44) } Button { debugPrint("World") } label: { Text("World") .frame(height: 44) } Text("Hoge") .frame(height: 44) .contentShape(Rectangle()) .onTapGesture { debugPrint("Hoge") } } .sheet(isPresented: $isModalPresented) { ContentView() } } }
5
5
367
3w
Unable to scroll the list under View.safeAreaInset()
Hello, Just noticed an issue with the .safeAreaInset() and .safeAreaPadding() modifiers. On iOS 18 beta 8, I'm unable to scroll the list or any other scrollable views within the safe area. This behavior is different compared to iOS 17/16. For example, adding a floating button using the .safeAreaInset() modifier: On iOS 18, the list cannot be scrolled or interacted within the bottom circled area.
2
1
211
3w
contextMenu and right click
Hi, I made a "Finder view" with SwiftUI, how is it possible to call viewModel.selectFileWithAnimation(file) when .contextMenu show? Thank you! @StateObject private var viewModel = FilesViewModel() // Use the view model to manage data and logic var body: some View { VStack { // Horizontal scrolling of files and folders ScrollView(.horizontal, showsIndicators: false) { if viewModel.sortedAndFilteredFolderContents.isEmpty { // Show "No Results" if no files or folders found Text("No Results") .font(.headline) .foregroundColor(.almostWhite) .padding() } else { HStack(spacing: 20) { ForEach(viewModel.sortedAndFilteredFolderContents, id: \.self) { file in VStack { ZStack { // Selection effect without matchedGeometryEffect if viewModel.selectedFile == file { RoundedRectangle(cornerRadius: 10) .fill(Color.blue.opacity(0.2)) .transition(.opacity) .frame(width: 80, height: 100) .animation(.easeInOut(duration: 0.3), value: viewModel.selectedFile) } VStack { Image(nsImage: viewModel.getFileIcon(for: file)) .resizable() .frame(width: 64, height: 64) .onTapGesture(count: 2) { // Select and open file/folder on double-tap viewModel.selectFileWithAnimation(file) viewModel.openFileOrFolder(file) } .onTapGesture { viewModel.selectFileWithAnimation(file) } .onLongPressGesture(minimumDuration: 0.5) { // Rename file with long press viewModel.rename(file) } .contextMenu { // Define your context menu buttons here Button(action: { viewModel.showInFinder(file) }) { Text("Show in Finder") Image(systemName: "folder") } Button(action: { viewModel.moveToTrash(file) }) { Text("Move to Trash") Image(systemName: "trash") } Button(action: { viewModel.rename(file) }) { Text("Rename") Image(systemName: "pencil") } Button(action: { viewModel.makeAlias(for: file) }) { Text("Make Alias") Image(systemName: "link") } Button(action: { viewModel.compress(file) }) { Text("Compress \(file.lastPathComponent)") Image(systemName: "archivebox") } Button(action: { viewModel.copyFile(file) }) { Text("Copy") Image(systemName: "doc.on.doc") } Button(action: { viewModel.shareFile(file, in: dynaClip.view) }) { Text("Share") Image(systemName: "square.and.arrow.up") } } Text(file.lastPathComponent) .font(.caption) .lineLimit(1) .truncationMode(.tail) .frame(width: 80) } } } } } .padding(.top, 20) } }
1
0
165
3w
How to make an updatable ForEach loop SwiftUI
I have a ForEach loop in my code which is used to display text per child of an array (i think it's an array). var flags: [String: Any] = [ "Flag1": "FlagValue" // More values will go here, by default there are no values (but can be // loaded in) ] And this is my code // CONTENT HStack { VStack { ForEach(0...flags.count, id: \.self) { flag in Text("hey") } } } When I start the app there's only one "hey" and no more will show up when I add more flags.
10
0
241
3w
AsyncImage returning Unknown Context error
Hello. On Xcode 15 I am trying to use AsyncImage to display an image from a URL. Whey I try, I get this in error: The operation couldn't be completed. (SwiftUI.AsyncImage<SwiftUI._ConditionalContent <SwiftUl._ConditionalContent<SwiftUI.Text, SwiftUI.Text>, SwiftUI._ConditionalContent<SwiftUI.Text, SwiftUI.Text>>>.(unknown context at $1c552a084).LoadingError error 1.) The view is simple, a VStack containing the AsyncImage call with a known good URL: import SwiftUI struct SetRowView: View { var set: MagicSet var body: some View { VStack { AsyncImage(url: URL(string: set.icon_svg_uri)) { phase in if let image = phase.image { image } else if phase.error != nil { Text(phase.error!.localizedDescription.debugDescription) } } } } } I've even hard-coded the URL to the image I want to load. Same result. I can't find any reference to this error at all.
0
0
114
3w