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

SwiftUI Documentation

Posts under SwiftUI tag

2,930 results found
Sort by:
Post not yet marked as solved
67 Views

PageTabViewStyle is causing vague SIGABRT crash (FB8984414)

PageTabViewStyle is causing a crash amongst a significant portion of my users and I've been unable to reproduce this issue. I've first written about this in this post from 4 months ago, after which I've reached out to DTS. Since then I've been able to narrow down the cause to PageTabViewStyle, with the logs suggesting its a SwiftUI framework issue. DTS at the time had no clue and instructed me to file a bug report (FB8984414), but I haven't heard anything about it. Latest reply from DTS a while ago was that they have no information on the matter. So ever since I've removed PageTabViewStyle (in part because it was used in onboarding) and avoided using it. Now with the extra activity here by engineers during dub-dub I was hoping I could get some answers. I've scheduled labs to ask about it, but figured I might be able to save everyone some time and open up the slot to others, should I be able to get an answer on this. The two burning questions would be: Is/was this a bug, if so is it resolved? If not, how to prevent the SIGABRT Text of the bug report below: A whole bunch of my users are experiencing consistent crashes after I’ve implemented scrolling pages by adding the .tabViewStyle(PageTabViewStyle()) modified to a TabView. Despite them reporting a 100% crash rate whenever they try to bring up the View that has the offending TabView, I am unable to reproduce this issue myself, making it impossible for me to provide useful steps to reproduce the issue or to provide a minimal working example. Instead I will be providing Swift files that contain the offending code. The crash logs that I have received, and included with this bug report, don’t indicate clearly what the cause of the SIGABRT is, but based on information provided by users I started suspecting the issue lied with the specific TabViewStyle. I verified this suspicion by commenting out the TabView code and have a handful of users that reported consistent issues test out this new build on TestFlight. The results were 0 crashes, further confirming my suspicions. I will also include the Swift files of this build. After this I reached out to Developer Technical Support and they instructed me to file this bug report.
Asked Last updated
.
Post not yet marked as solved
83 Views

@SectionedFetchRequest using relationship as sectionIdentifier

As the title says I'm trying to use a to-one relationship as a sectionIdentifier in a @SectionedFetchRequest. The compiler is happy but there's a runtime crash: Could not cast value of type '_NSCoreDataTaggedObjectID' (0x146c0f750) to 'MyApp.ServiceCategory' (0x104c4b3a0). The fetch request: @SectionedFetchRequest(     sectionIdentifier: \Service.serviceCategory,     sortDescriptors: [       SortDescriptor(\Service.active, order: .reverse),       SortDescriptor(\Service.displayText)     ],     predicate: NSPredicate(format: "%K = %d", #keyPath(Service.active), true),     animation: .default   ) var sectionedServices: SectionedFetchResults<ServiceCategory?, Service> ... and the breaking runtime code: ForEach(sectionedServices /* here */) { section in Section(header: Text(section.id?.displayText ?? "")) { ForEach(section) { svc in Text(svc.displayText ?? "") } } } The request works if I switch out the sectionIdentifier for the active property (which is a Bool property rather than a relationship). It also works if I switch it out for displayText which is an optional String, so it seems to be a problem trying to section by a relationship rather than with it being an optional. The error suggests the request is returning a Core Data fault rather than an object but my attempts to somehow unwrap this haven't gone very far. Any thoughts would be greatly appreciated!
Asked
by robwuk.
Last updated
.
Post not yet marked as solved
172 Views

SwiftUI's DragGesture broken in Catalyst apps on macOS 11?

I have a Mac Catalyst app with some custom SwiftUI sliders. After upgrading to macOS Big Sur I've noticed that the sliders are difficult to use. After some digging and debugging it looks like the DragGesture is interrupted (i.e. stopped without calling onEnded) as soon as the cursor leaves the dragged view's frame. So, if you drag slowly everything's good, go a bit faster and you 'loose' the knob. In iOS, iPadOS and Catalina the same code works just fine. I have filed this to Apple using the Feedback Assistant, but thought that maybe you'll have some thoughts on this or maybe a workaround ideas. Have you got any? Kind regards, Jan
Asked
by JanPru.
Last updated
.
Post not yet marked as solved
18 Views

Global variable

Hey! Is there any opportunity in SwiftUI to keep a global variable that can changed its value and not cause views refresh (because I'm not going to display the value of this var)?
Asked Last updated
.
Post not yet marked as solved
18 Views

(Swift + CloudKit) or (SwiftUi + Core Data + CloudKit)

Hello everyone! Im new to SwiftUI and I have been trying to pinpoint the best approach when sending and receiving data using CloudKit. Is Core Data absolutely necessary to use when building an app with SwiftUI and CloudKit? I've read that Core Data is falling off, which is why I'm questionable on spending time learning it. Couldn't I simply use SwiftUI and CloudKit without the use of anything else? I do know that Core Data is NOT necessary when using CloudKit while writing Objective C, but I am wanting to stick solely with Swift as I have been told that Obj C is falling off too. Thanks for the help!
Asked
by Misaiah.
Last updated
.
Post not yet marked as solved
207 Views

SwiftUI 2 collapse section headers by default

Is there a way to have the new List > Section collapsible headers be collapsed by default. I have a list section of upcoming events which should be shown but then I have another section of historical events which I would prefer to be collapsed by default. The app is for iOS only so no APIs from Mac OS
Asked
by iShaymus.
Last updated
.
Post not yet marked as solved
14 Views

Dropping text on a TextField

Is it possible to disable this feature in swiftUI ? So that the user of my app has to type every character on the keyboard (don't ask why :)
Asked
by fu531aht.
Last updated
.
Post not yet marked as solved
30 Views

EnvironmentObject access

Hi! I'm learning SwiftUI and now got stuck with a problem of using @EnvironmentObject. The problem is: I get an email inputed by user and I have to pass it through several view (each view I call with NavigationLink). But I get an error sometimes: struct RepeatPinView: View {   @State var pin: String   @State var pinRepeat: String = ""   @State var text: String = "Repeat PIN"   @State var selection: String? = nil       @EnvironmentObject var globalObj: GlobalObj   @Environment(\.colorScheme) var colorScheme       var body: some View {           let buttons: [[numPadButton]] = [       [.one, .two, .three],       [.four, .five, .six],       [.seven, .eight, .nine],       [.dop, .zero, .del],     ]           VStack {       NavigationLink(destination: ContentView(), tag: "GotPin", selection: $selection) { EmptyView() }       Spacer() //      Text("Pin repeat \(globalObj.email)") /* here I'm trying to check the email but sometimes and sometimes not (whaat.. can't understand how it works) I get a Fatal error: No ObservableObject of type GlobalObj found */       Text(text)         .font(.system(size: 30))       Spacer()       Text(pinRepeat)         .font(.system(size: 30))         .onChange(of: pinRepeat) { pinRepeat in           print(pinRepeat) //          print(globalObj.email) /* same problem, sometimes get a Fatal error*/           if pinRepeat.count == 4 {             if self.pinRepeat == pin {               print(globalObj.email)               let textToWrite = globalObj.email + "\n" + pinRepeat print(textToWrite) /* surprisingly, but here everything works fine WHY??? */               selection = "GotPin"             } else {               text = "Try again"             }           }         }         .frame(width: 100, height: 50, alignment: .center)       Spacer()       ForEach(buttons, id: \.self) { row in         HStack {           ForEach(row, id: \.self) { item in             Button(action: {               switch item.rawValue {               case "dop":                 print("dop")               case "del":                 print("del")                 if pinRepeat != "" {                   pinRepeat.removeLast()                 }               default:                 pinRepeat.append(item.rawValue)               }             }, label: {               if item.rawValue == "del" {                 Image(systemName: "delete.left")                   .font(.title)                   .foregroundColor(colorScheme == .dark ? .white : .black)                   .padding()               } else if item.rawValue == "dop" {                 Text("")                   .font(.title)                   .foregroundColor(colorScheme == .dark ? .white : .black)                   .padding()               } else {                 Text(item.rawValue)                   .fontWeight(.bold)                   .font(.largeTitle)                   .foregroundColor(colorScheme == .dark ? .white : .black)                   .padding()                   .background(                     Circle()                       .stroke(Color.yellow, lineWidth: 4)                       .frame(width: buttonWidth(item: item) - 5, height: buttonHeight(item: item) - 5, alignment: .center)                   )               }             })             .frame(width: buttonWidth(item: item), height: buttonHeight(item: item), alignment: .center)             .padding([.trailing, .leading], 7)                         }         }         .padding(.bottom, 7)       }       Spacer()       Spacer()       Spacer()     }   } } In previous views (there are three views before this one) I never got a Fatal error doing the same things. Help me, please
Asked Last updated
.
Post not yet marked as solved
101 Views

Form vs Vstack for SwiftUI for iOS

I'm building a View for account creation, and have a number of text fields (first name, last name, email, etc.). It seems like the natural choice is to embed these TextField() views into a Form, but given that Form is built on UITableView (as I understand it) it becomes challenging and requires some workarounds to add modifiers like .background() and have them perform the way I want them to. If, instead of embedding them in a Form, I just use a VStack, there's no problem. So my question is, is there any reason I should put up with the trouble and use Form? Does it give me any added functionality? Is it considered bad or unclean code to not use Form? From what I can tell, there don't seem to be any real benefits, right?
Asked
by Shen3443.
Last updated
.
Post marked as solved
78 Views

Activating SwiftUI buttons with a custom ButtonStyle using Keyboard Focus on macOS

Hey all, Currently tested in Xcode 13 / BigSur It seems the keyboard focus feature of macOS does not work with any Button in SwiftUI that uses a custom ButtonStyle. You can attach the .focusable() modifier to the Button (or ButtonStyle) to allow Tab / Shift+Tab navigation between buttons, however pressing Space does not execute the button as expected. Is there something I'm missing? or is this intentionally not supported? To work around this, all I can think of is using a UIRepresentableView around NSButton, however I'd like to avoid that if possible. Here is an example View to show the problem: https://gist.github.com/deanPGM/71ddfbe87a47454d220b16809a489f69
Asked
by dtc1.
Last updated
.
Post not yet marked as solved
15 Views

Does SwiftUI cache images in memory?

I have a VStack of views where each view contains an ArtworkView: struct ArtworkView: View {   let artworkId: UInt64   @State private var uiImage: UIImage?   @Environment(\.scenePhase) var scenePhase   @ViewBuilder var imageView: some View {     if let uiImage = uiImage {       Image(uiImage: uiImage)     }     else {       Image(systemName: "photo").opacity(0.4)     }   }   var body: some View {     imageView       .onAppear() {         loadArtwork(withId: artworkId) {           uiImage = $0         }       }       .onChange(of: scenePhase) { scenePhase in         if scenePhase == .background {           uiImage = nil         }       }   } } At first sight it works as expected – images appear on launch and disappear upon transition to the background. But when I profile with Instruments > Allocations there is no difference in memory usage between foreground and background. And I need images to be unloaded from memory in background. Does SwiftUI VStack or Image cache underlying UIImage objects and if so, how to opt out of it?
Asked
by okla.
Last updated
.
Post not yet marked as solved
61 Views

SwiftUI: Markdown support for string variables

Text in iOS 15 Beta 1 (Xcode 13 Beta 1) only handles markdown when string literal was passed to initializer. struct MarkdownTest: View {   var text: String = "**Hello** *World*"   var body: some View {     VStack {       Text("**Hello** *World*") // will be rendered with markdown formatting       Text(text) // will NOT be rendered according to markdown     }   } } struct MarkdownTestPreviews: PreviewProvider {   static var previews: some View {     MarkdownTest()   } } Is this a known bug or do I have to create an entry in Feedback Assistant?
Asked Last updated
.
Post not yet marked as solved
19 Views

EXC_BAD_INSTRUCTION awating Task.sleep

Trying to use the following ObservableObject backed by an actor and getting an error when awaiting Task.sleep EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) Any ideas? class Reader: ObservableObject {     static let shared = Reader(actor: .init())     let actor: TestActor     @Published var val = 0     @MainActor func read() async {         val = await actor.val     }     func increment() async -> Bool {         await actor.increment()         await read()         return true     }     init(actor: TestActor) {         self.actor = actor     } } actor TestActor {     var val = 0     func increment() async {         let oldval = val         await Task.sleep(2000000000) // Error here!         val += 1     } }```
Asked Last updated
.
Post not yet marked as solved
2.3k Views

SwiftUI iOS 14 MapKit Annotation Tap Gesture (didSelect)

After spending two hours trying to find anything on it (and failing), I hope for a last resort here: I have a very simple map with annotation markers. Problem: the user taps on a marker or pin — and in the past it used to fire a "didSelect" on the mapView, but now?! How do I react to the user tapping a pin or marker? I tried to add a .onTapGesture but no such thing. Map(   coordinateRegion: $viewMapModel.mapLocation,   annotationItems: viewMapModel.annotations,   annotationContent: { &#9;&#9;n in MapMarker( &#9;&#9;&#9;coordinate: n.location, &#9;&#9;&#9;tint: .red &#9;&#9;) &#9;} ) Essentially, once a user taps a pin or marker, I want to show a popup, but just showing a print would already make my world for simplicity purposes here. I want to use this new iOS 14+ format, so please no solutions taking me back to makeUIView->MKMapView stuff. Thanks!
Asked Last updated
.