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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Setting launch screen image through info.plist - image stretches to cover full screen
I am developing an app in swiftUI using Xcode 12.3, deployment target iOS 14.0. The launch screen is setup through info.plist by specifying 'background color' and 'image name'. The file used in 'image name' is from Assets catalog. (PNG format, size300 x 300 and corresponding @2x and @3x resolutions) What I have observed, when the app is installed for the first time the launch image is centered and have original resolutions but all subsequent launches show launch images stretched to cover full screen. Any ideas why this is happening and how to have more consistent behavior either way? I have tried 'respect safe area' option but it does not make a difference. Thank you.
11
2
9.0k
Jan ’21
SwiftUI Laggy on a Real Device
I have recently started Beta Testing my SwiftUI App on my iPhone 6s, previously I was testing it on the iPhone 12 Simulator. While Testing on the Real Device I encountered issues like: CPU going past 98% Really Laggy ScrollView Tab Bar Freezes Randomly Since My app is going to go in Production State in a few days, Since this is my first iOS App as well, I am not too sure if these issues are because of SwiftUI, my Phone or what, I have asked Apple Support but, haven't received a response so far. My App Stats: Lines of Code: ~1,500 CPU Usage on Simulator: Max. 10% Bundle Size: 2MB RAM Max. on Simulator: 32.3mb
2
0
4.3k
Jan ’21
ChildView in FullScreenCover is recreated every time if ContentView is updated
Hi guys. I have a question related to the next behavior. I have ContentView with a list of views where the corresponding view models are passed. The user can click by some view. At the moment full-screen modal dialog will be shown according to the passed type. It's fine. At some time my view models are being updated and the whole ContentView will be reloaded. The problem is: fullScreenCover is called and ChildEventView is recreated. How to prevent recreating ChildEventView? struct ContentView: View { 		@ObservedObject private var eventListViewModel = EventListViewModel() 		@State private var fullScreenType: FullScreenType? 		/* some stuff */ 		var body: some View { 				ScrollView { 						LazyVStack { 								ForEach(eventListViewModel.cardStates.indices, id: \.self) { index in 										let eventVM = eventListViewModel.eventVMs[index] 										EventCardView(eventViewModel: eventVM, eventId: $selectedEvent.eventId) { 												self.fullScreenType = .type1 										} 										/* some other views */ 								} 						} 				}	 				.fullScreenCover(item: $fullScreenType, onDismiss: { 						self.fullScreenType = nil 				}, content: { fullScreenType in 						switch fullScreenType { 								case .type1: 								return ChildEventView(selectedEvent.eventId).eraseToAnyView() 								/* some other cases */ 						} 				}) 		} }
2
0
1.3k
Jan ’21
Universal Links Camera does not pass url to .onOpenURL (perform :) method SwiftUI Xcode
Hello, I connected Universal Links between the website and the application, everything was done according to the official documentation, and everything works fine, when the site is launched, safari offers to launch the application, there is also a banner above the launch page. In SwiftUI, I listen to the URL via .onOpenURL (perform :), everything works, but if the link is encoded in a QR code and scanned through the camera, a plate will appear prompting you to go to the application, and it goes, but only does not pass the URL to the .onOpenURL method (perform: ) . What could be the problem ?
3
4
3.8k
Feb ’21
SwiftUI App crashes in main method on Startup (macOS 11)
Hi, my app sees quite a lot of crashes (crash report below) and I have no clue how to debug the problem any further. The problems seems only to occur on macOS 11. Is there anyone als having this kind of problems? Are there fixes/workarounds? The source code of my app is open source - https://github.com/PDF-Archiver/PDF-Archiver if anyone would like to have a look into it. OS Version: macOS 11.2.2 (20D80) Report Version: 104 Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: ILL_NOOP at 0x00007fff2ca430f4 Crashed Thread: 0 Application Specific Information: Fatal error SwiftUI Thread 0 Crashed: 0 libswiftCore.dylib 0xfffe591310f4 _assertionFailure 1 SwiftUI 0xfffe8516c6fc ViewCache.commitPlacedChildren 2 SwiftUI 0xfffe850727f4 IncrementalChildPlacements.updateValue 3 SwiftUI 0xfffe8512890e Attribute.initT 4 AttributeGraph 0xfffe8625b17e AG::Graph::UpdateStack::update 5 AttributeGraph 0xfffe8625b607 AG::Graph::update_attribute 6 AttributeGraph 0xfffe862638f2 AG::Subgraph::update 7 SwiftUI 0xfffe85463679 GraphHost.runTransaction 8 SwiftUI 0xfffe85464bce GraphHost.runTransaction 9 SwiftUI 0xfffe85463ec8 GraphHost.flushTransactions 10 SwiftUI 0xfffe85464b6e GraphHost.asyncTransactionT 11 SwiftUI 0xfffe85464738 @callee_guaranteed 12 SwiftUI 0xfffe84d172b0 ViewGraphDelegate.updateGraphT 13 SwiftUI 0xfffe853201b9 ViewRendererHost.updateViewGraphT 14 SwiftUI 0xfffe8531e2a8 ViewRendererHost.updateViewGraphT 15 SwiftUI 0xfffe85329e98 NSHostingViewT 16 SwiftUI 0xfffe84d12f06 ViewGraphDelegate.updateGraphT 17 SwiftUI 0xfffe84d17258 NSHostingViewT 18 SwiftUI 0xfffe85464b49 GraphHost.init 19 SwiftUI 0xfffe84d18c9b @callee_guaranteed 20 SwiftUI 0xfffe8537a250 @callee_guaranteed 21 SwiftUI 0xfffe85377ee5 NSRunLoop.flushObservers 22 SwiftUI 0xfffe8537a198 NSRunLoop.addObserver 23 SwiftUI 0xfffe853755fd @callee_guaranteed 24 libswiftObjectiveC.dylib 0xfffe66ed2d9d autoreleasepoolT 25 SwiftUI 0xfffe8537a182 NSRunLoop.addObserver 26 SwiftUI 0xfffe8537a1ca NSRunLoop.addObserver 27 CoreFoundation 0xfffe40ab4dac __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ 28 CoreFoundation 0xfffe40ab4c3c __CFRunLoopDoObservers 29 CoreFoundation 0xfffe40ab3745 CFRunLoopRunSpecific 30 HIToolbox 0xfffe5101162f RunCurrentEventLoopInMode 31 HIToolbox 0xfffe5101142b ReceiveNextEventCommon 32 HIToolbox 0xfffe5101114e _BlockUntilNextEventMatchingListInModeWithFilter 33 AppKit 0xfffe45b349b0 _DPSNextEvent 34 AppKit 0xfffe45b33176 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] 35 AppKit 0xfffe45b25689 -[NSApplication run] 36 AppKit 0xfffe45af996e NSApplicationMain 37 SwiftUI 0xfffe84ab59f3 runApp 38 SwiftUI 0xfffe8534c791 runAppT 39 SwiftUI 0xfffe84ecb09c App.main 40 PDFArchiver 0x2067699b0 [inlined] PDFArchiverApp.$main 41 PDFArchiver 0x2067699b0 main 42 libdyld.dylib 0xfffe40967620 start Crash Report - https://developer.apple.com/forums/content/attachment/8bc85490-ee29-4233-91e2-63ff3cd0d3b8
3
0
3.6k
Feb ’21
Landmarks Tutorial. Preview doesn't work
Hi everyone, I'm trying to follow the Landmarks project tutorial and got stuck in the second part, in the second section (Create the Row View), step 6 where it says "Modify the text view to use the landmark property’s name." This must be done in the LandmarkRow.swift file. https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation The tutorial shows that after doing this, the preview will display the name of the landmark (Turtle Rock) instead of the usual "Hello world" greeting. But my replacement is not happening. Moreover, from this point on, the preview stops working. There are no error messages in the code, except for the message that the preview could not be performed. I checked and rewrote the code several times, replaced the data source files, but nothing helped. At the same time, the preview works well in other view files. I can't figure out what's wrong with my code? Any ideas as to what the reason will be is appreciated. Below is the code of two files, the LandmarkRow.swift, where view does not work, the second is ModelData.swift and it is related to the previous one. LandmarkRow.swift import SwiftUI struct LandmarkRow: View {     var landmark: Landmark     var body: some View {         HStack {             landmark.image                 .resizable()                 .frame(width: 50, height: 50)             Text(landmark.name)             Spacer()         }     } } struct LandmarkRow_Previews: PreviewProvider {     static var previews: some View {         LandmarkRow(landmark: landmarks[0])     } } ModelData.swift import Foundation var landmarks: [Landmark] = load("landmarkData.json") func loadT: Decodable(_ filename: String) - T {     let data: Data     guard let file = Bundle.main.url(forResource: filename, withExtension: nil)     else {         fatalError("Couldn't find \(filename) in main bundle")     }     do {         data = try Data(contentsOf: file)     } catch {         fatalError("Couldn't load \(filename) from main bundle:\n\(error)")     }     do {         let decoder = JSONDecoder()         return try decoder.decode(T.self, from: data)     } catch {         fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")     } }
7
1
2.9k
Mar ’21
SwiftUI NavigationLink pops out by itself
I have a simple use case where a screen pushes another screen using the NavigationLink. There is a strange behaviour iOS 14.5 beta where the pushed screen is popped just after being pushed. I manage to create a sample app where I reproduce it. I believe the cause is the presence of @Environment(\.presentationMode) that seem to re-create the view and it causes the pushed view to be popped. The exact same code works fine in Xcode 12 / iOS 14.4 Here is a sample code. swift import SwiftUI public struct FirstScreen: View {   public init() {}   public var body: some View {     NavigationView {       List {         row         row         row       }     }   }   private var row: some View {     NavigationLink(destination: SecondScreen()) {       Text("Row")     }   } } struct SecondScreen: View {   @Environment(\.presentationMode) var presentationMode: BindingPresentationMode   public var body: some View {     VStack(spacing: 10) {       NavigationLink(destination: thirdScreenA) {         Text("Link to Third Screen A")       }       NavigationLink(destination: thirdScreenB) {         Text("Link to Third Screen B")       }       Button("Go back", action: { presentationMode.wrappedValue.dismiss() })     }   }   var thirdScreenA: some View {     Text("thirdScreenA")   }   var thirdScreenB: some View {     Text("thirdScreenB")   } } struct FirstScreen_Previews: PreviewProvider {   static var previews: some View {     FirstScreen()   } }
55
2
53k
Apr ’21
ScrollViewReader scrollTo ignores withAnimation-Duration
I tried animating the scrollTo() like so, as described in the docs. - https://developer.apple.com/documentation/swiftui/scrollviewreader swift withAnimation { scrollProxy.scrollTo(index, anchor: .center) } the result is the same as if I do swift withAnimation(Animation.easeIn(duration: 20)) {     scrollProxy.scrollTo(progress.currentIndex, anchor: .center) } I tried this using the example from the ScrollViewReader docs. With the result that up and down scrolling has exactly the same animation. struct ScrollingView: View {     @Namespace var topID     @Namespace var bottomID     var body: some View {         ScrollViewReader { proxy in             ScrollView {                 Button("Scroll to Bottom") {                     withAnimation {                         proxy.scrollTo(bottomID)                     }                 }                 .id(topID)                 VStack(spacing: 0) {                     ForEach(0..100) { i in                         color(fraction: Double(i) / 100)                             .frame(height: 32)                     }                 }                 Button("Top") {                     withAnimation(Animation.linear(duration: 20)) {                         proxy.scrollTo(topID)                     }                 }                 .id(bottomID)             }         }     }     func color(fraction: Double) - Color {         Color(red: fraction, green: 1 - fraction, blue: 0.5)     } } struct ScrollingView_Previews: PreviewProvider {     static var previews: some View {         ScrollingView()     } }
10
5
3.4k
Apr ’21
Expected Expression Error Swiftui
i get the expected expression error every time i restart Xcode i have tried numerous times to fix it here is the code import SwiftUI struct MainView: View {          var body: some View {                  Color(.secondarySystemBackground)         HStack{         }         NavigationView{                                       Text("")                 .navigationTitle("Home")                          } navigationBarItems(trailing: Button(action: { print("Hello") }) { Image(systemName: "square.and.pencil") .resizable() .frame(width: 50, height: 50) ) - Error Here             }         } } struct MainView_Previews: PreviewProvider {     static var previews: some View {         MainView()     } }
4
0
3.5k
Apr ’21
fileImporter not showing
Hello, in my Mac Catalyst app, I have detail view with sections modeled as DisclosureGroups. The label view has a button, that shall trigger a file import view when pushed. The label view is defined as follows: swift HStack {         Text(LocalizedStringKey("Documents")).font(.title)         Spacer()         Button {           showFileImporter = false           // fix broken picker sheet           DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {             showFileImporter = true           }         } label: {           Image(systemName: "doc.badge.plus")             .padding(.horizontal, 10)         }         .disabled(!expanded)         .fileImporter(                       isPresented: $showFileImporter,               allowedContentTypes: [.data],           allowsMultipleSelection: false) { result in                       // add fileUrl.startAccessingSecurityScopedResource() before accessing file             NSLog("\(result)")           }       } Unfortunately the file import view is not showing, when the button is pushed, although the state changes to true. Does anybody have any hints? BTW the repo is available at https://github.com/thbonk/repti/tree/ui-refactoring The view in question is https://github.com/thbonk/repti/blob/ui-refactoring/Repti/Source/UI/Views/IndividualDetails/DocumentsSubview.swift Thanks & Best regards Thomas
1
0
1k
May ’21
SwiftUI preview failing with failedToGenerateThunkInfo
I have an iOS app by using a swift package to hold most of the logic. However, the previews of SwiftUI views often fail with following error: HumanReadableSwiftError BuildError: failedToGenerateThunkInfo(Error Domain=com.apple.xcbuild Code=19 "could not generate preview info: noTargetBuildGraph" UserInfo={NSLocalizedDescription=could not generate preview info: noTargetBuildGraph}) To reproduce this, please clone https://github.com/pointfreeco/isowords and check for preview of ChangelogView.
10
0
2.5k
May ’21
[SwiftUI] How do I catch the "No image named MYEXAMPLE found in asset catalog" warning? Alternatively, how do I determine if something exists in the asset catalog?
I'm trying to store image data locally and the name of the image is retrieved from an API. In the situation where an image does not exist locally, I want to put a placeholder. Right now it just puts a white background. Whenever I retrieve from the API I get a purple exclamation which is a warning but not an exception. How can I intercept this warning and make it show a placeholder instead? One problem is that Image is not an optional. It just blithely accepts whatever is fed into it which is annoying. Is there a way to query the asset catalog if it contains something?
1
0
693
Jun ’21
AsyncImage - Cancelled Loading before View is Visible
I have been playing around with the new AsyncImage Api in SwiftUI I am using the initialiser that passes in a closure with the AsyncImagePhase, to view why an image may not load, when I looked at the error that is passed in if the phase is failure, the localised description of the error is "Cancelled" but this is happening before the view is being displayed. I am loading these images in a list, I imagine I am probably doing something which is causing the system to decide to cancel the loading, but I cannot see what. Are there any tips to investigate this further?
13
6
9.4k
Jun ’21
[Critical Issue] Content with variable height in a LazyVStack inside a ScrollView causes stuttering / jumping
My goal is to create a chat view in SwiftUI. This requires creating a ScrollView with content of varying heights . After extensive debugging, I've determined that if you have views within a LazyVStack inside of a ScrollView that do not have a fixed height, it will stutter when you scroll to the top of the view. –––– PROJECT: Download this project and try for yourself struct ContentView: View { @State var items: [String] = MockData.randomMessages(count: 100) var body: some View { VStack { Button("Shuffle items") { items = MockData.randomMessages(count: 100) } ScrollView { LazyVStack(spacing: 10) { ForEach(Array(items.enumerated()), id: \.offset) { index, item in Text(item) .background(colors.randomElement()!) } } } } } } My conclusion right now is that LazyVStack only works with child views that have fixed height. This issue alone prevents SwiftUI from being production ready. Has anyone else tackled this?
7
6
6.7k
Jul ’21
How to declare a TableColumn with nullable field?
How does one declare a TableColumn with a nullable field? I have a Book model with several nullable fields: struct Book: Codable, Equatable, Identifiable { // ... let productURL: String? // ... } This is how I'm trying define the corresponding TableColumn: TableColumn("Product URL", value: \.productURL) { book in Text(String(book.productURL ?? "")) } Though this results in several errors: Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires that 'Book' inherit from 'NSObject' Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires that 'Book' inherit from 'NSObject' Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires the types 'KeyPathComparator' and 'SortDescriptor' be equivalent Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires the types 'KeyPathComparator' and 'SortDescriptor' be equivalent Other, non-nullable columns work just fine. For example: TableColumn("ID", value: \.id) { book in     Text(String(book.id)) } TableColumn("Slug", value: \.slug) TableColumn("Category", value: \.category) TableColumn("Title", value: \.title) // ...
8
0
2.7k
Aug ’21
Conforming @MainActor class to Codable
How does one add Codable conformance to a class that needs to be isolated to the MainActor? For example, the following code gives compiler errors: @MainActor final class MyClass: Codable { var value: Int enum CodingKeys: String, CodingKey { case value } init(from decoder: Decoder) throws { // <-- Compiler error: Initializer 'init(from:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Decodable' let data = try decoder.container(keyedBy: CodingKeys.self) self.value = try data.decode(Int.self, forKey: .value) } func encode(to encoder: Encoder) throws { // <-- Compiler error: Instance method 'encode(to:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Encodable' var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(value, forKey: .value) } } I'm definitely struggling to get my head around actors and @MainActor at the moment!
1
1
2.7k
Aug ’21
SwiftUI MagnificationGesture broken in iPadOS 15?
The following code is shown on apples documentation page for SwiftUI MagnificationGesture: struct MagnificationGestureView: View { @GestureState var magnifyBy = CGFloat(1.0) var magnification: some Gesture { MagnificationGesture() .updating($magnifyBy) { currentState, gestureState, transaction in gestureState = currentState } } var body: some View { Circle() .frame(width: 100 * magnifyBy, height: 100 * magnifyBy, alignment: .center) .gesture(magnification) } } Try it (on device) in the Swift Playgrounds App by prepending import SwiftUI import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.setLiveView(MagnificationGestureView()) or as a compiled app using the app template in Xcode and try to scale the circle to different sizes in succession. On iPadOS 14 everything works as expected, but since iPadOS 15 Beta 2 it hangs after a few movements of the fingers. Does it work for you? What am I doing wrong? I already filed feedback, but the problem remains till the current beta version and I don't know how to get the gestures working again?
5
0
1.6k
Sep ’21