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

SwiftUI Timer not working inside Menu bar extra
Hello, I am new to the Swift and the SwiftUI. I want to build a MacOS app for learning purpose. Looks like I am stuck, so looking for some help. The code below does not execute the print statement. Why is the timer not working? What am I missing? Thanks in advance. struct CustomView: View {         let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()     private var nums: [String] = ["one", "two"]         var body: some View {         ForEach(nums, id: \.self) {num in             Text(num)         }         .onReceive(timer) { time in // why is this not working?             print("time is \(time)")         }     } } @main struct Writer: App {     var body: some Scene {         MenuBarExtra("Writer util", systemImage: "pencil.line") {             CustomView()         }         .menuBarExtraStyle(.menu)     } }
6
1
1.3k
Oct ’23
DisclosureGroup with Table
Does embedding a Table inside a DisclosureGroup not work? If I uncomment the DisclosureGroup in the code below, the table doesn't display. Is there anything that I can do to make it work? import SwiftUI import PlaygroundSupport class Foo: Identifiable {     let id: Int     let num: Double          init(id: Int, num: Double) {         self.id = id         self.num = num     } } typealias FooArray = [Foo] struct ContentView: View {     @State var foos: FooArray = [         Foo(id: 1, num:0.0 ),         Foo(id: 2, num:0.1 ),         Foo(id: 3, num:0.2 ),         Foo(id: 4, num:0.3 )     ]     @State private var revealFoos = true     var body: some View {         VStack {             Text("Foo")                 .font(.title)                 .bold()             Divider()                          //DisclosureGroup("Foos", isExpanded: $revealFoos) {                 FooTable(foos: foos)             //}                          Spacer()         }     } } struct FooTable : View {     var foos: FooArray     @State private var sortOrder = [KeyPathComparator(\Foo.id, order: .reverse)]          var body: some View {         VStack {             Table(foos, sortOrder: $sortOrder) {                 TableColumn("ID", value: \.id) { value in                     Text(value.id.description)                 }                 TableColumn("Number", value: \.num) { value in                     Text(value.num.description)                         .frame(maxWidth: .infinity, alignment: .trailing)                 }             }         }     } } PlaygroundPage.current.setLiveView(ContentView())
1
0
536
Aug ’23
iOS Widget not available in Widget Search on iOS 16
We are running into a major issue with building an iOS Widget. iOS Widgets are basically large informational app icons you can pin to your iPhone home screen (What is a widget?). iOS widgets were introduced in iOS 14. We’ve finished building our iOS widget. However, when half of our users attempt to search for our widget after downloading our app, our widget is not showing up in the widget search results. For the other half, it works fine. This seems to be somewhat of a bug from Apple, as it is affects other widget apps (Apple Thread, the problem exists for large widget apps also). It seems like we are having this issue far more, percentage-wise, than other widget apps. I’ve searched through nearly every resource online (StackOverflow, etc.), which is why I’m posting a question now. Things like deleting the app and reinstalling, restarting the phone, etc. have not been a fix either for these problematic users. It doesn't seem to be tied to any iOS version (14, 15, etc.). As I have iOS 15, and it works fine. But, some users with iOS 15 are getting the bug. Has anyone ran into this issue where a widget is not searchable? How did you fix it? Any resources are appreciated as I am at a major blocker right now. Since my app is primarily based on iOS widgets, this makes it basically unusable for certain users.
1
2
761
Oct ’23
Picker selection not changing
Hello, I have made a picker that is filled with data from an API endpoint. The data is retrieved and shown properly, however, when trying to change the selection on the picker, it does not work. For simple demonstration i have put the picker in a empty view. Here is the code: import SwiftUI struct TestView: View { struct Subject: Hashable { let subjectId: Int let subjectName: String } @State var subjects: [Subject] = [] @State var selectedSubject: Subject? = nil var body: some View { VStack { Picker(selection: $selectedSubject, label: Text("Kies een vak")) { ForEach(subjects, id: \.self) { subject in Text(subject.subjectName).tag(subject) } } .frame(width: 300, height: 50) .background(Color.black.opacity(0.05)) .cornerRadius(10) .onChange(of: selectedSubject) { newSubject in print("Chosen subject: \(newSubject?.subjectId ?? -1)") } Text("Chosen subject: \(selectedSubject?.subjectId ?? -1)") } .onAppear { Api().extractSubjects { subjects in DispatchQueue.main.async { self.subjects = subjects.map { TestView.Subject(subjectId: $0.subjectId, subjectName: $0.subjectName) } } } } } } To better illustrate what I mean i have made a screenrecording: I hope you guys and girls can help me out. If you need more info, please let me know! Any help or suggestion is greatly appreciated, thanks!
2
0
1.3k
Jan ’24
iOS 16.4 NavigationStack Behavior Unstable
I've tested the behavior of NavigationStack in iOS 16.4 and found that it doesn't work in my already published app. Of course, my app works perfectly fine with the NavigationStack in iOS 16 to iOS 16.3. I'm not sure about the cause, but when tapping on a NavigationLink in a very large and complex navigation hierarchy, the corresponding navigationDestination doesn't transition the screen and instead gets caught in an infinite loop. Has anyone else experienced similar issues? I'd like to prepare a sample program to reproduce the issue, but it doesn't occur in simple view hierarchies, so I haven't been able to prepare one yet. Although the release notes for iOS 16.4 mention changes related to the performance of the NavigationStack, I suspect that some instability has been introduced. This behavior reminds me of the unintended automatic pop issue in the NavigationView of iOS 15. In the iOS 16.4 environment, I am planning to revert to using NaviagtionView. Once I have prepared a sample program to reproduce the issue, I will update again. There are bugs in NaviagtionView as well, but in the iOS 16.4 environment, I am temporarily planning to revert to using it. Once I have prepared a sample program to reproduce the issue, I will update again.
9
9
3.2k
Oct ’23
Class CDPCAReporter is implemented in both...
Seeing these logs in the iOS 16.2 iPad Air simulator with a SwiftUI app. Clutters up the logs and clearly something implemented internal to the simulator. Any ideas on how to address the issue or suppress the logs? thanks objc[69650]: Class CDPCAReporter is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/CoreCDPInternal.framework/CoreCDPInternal (0x160b7d1d8) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/CoreCDP.framework/CoreCDP (0x159028eb0). One of the two will be used. Which one is undefined. objc[69650]: Class CDPCABackupRecoveryReporter is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/CoreCDPInternal.framework/CoreCDPInternal (0x160b7def8) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/CoreCDP.framework/CoreCDP (0x1590290e0). One of the two will be used. Which one is undefined.
2
4
1.2k
Aug ’23
NavigationSplitView how to disable the side bar, to make it like the reminder app in iPad?
I want to make it like this How to disable the button that open the side bar, I only need the content and the detail view. I don't need the sidebar view. Below is my code import SwiftUI @available(iOS 16.0, *) struct Screen: View { @ObservedObject var userData = UserData() @State private var isIntroShown = true @State var Itema: Bool = false @State private var showFoodDetail = false @State var rb: Bool = false @State var Setting: Bool = false @State var Recipe: Bool = false @Environment(\.defaultMinListRowHeight) var minRowHeight @Environment(\.colorScheme) var colorScheme @State private var searchText = "" private let adaptiveColumns = [ GridItem(.adaptive(minimum: 170)) ] var columns = Array(repeating: GridItem(.flexible(), spacing: 10), count: 2) var filteredRooms: [Room] { if searchText.isEmpty { return userData.rooms } else { return userData.rooms.filter { room in let foodNames = room.food.map { $0.name.lowercased() } return room.name.lowercased().contains(searchText.lowercased()) || foodNames.contains { $0.contains(searchText.lowercased()) } } } } @State private var columnVisibility = NavigationSplitViewVisibility.doubleColumn var body: some View { NavigationSplitView (columnVisibility: $columnVisibility){ } content: { ScrollView{ GridView() .padding(.horizontal) .padding(.bottom, 20) }.toolbar { ToolbarItem(placement: .bottomBar){ Button(action:{self.Itema = true}) { HStack { Image(systemName: "plus.circle.fill").resizable().frame(width: 20, height: 20).foregroundColor(.white) Text("New Item").foregroundColor(.white).bold() } } .sheet(isPresented: self.$Itema){ NewItem(userData: self.userData) } } ToolbarItem(placement: .bottomBar){ Button(action:{self.rb = true}) { HStack { Text("New Room").foregroundColor(.white) } } .sheet(isPresented: self.$rb){ NewRoom(userData: self.userData) } } ToolbarItem(placement: .navigationBarTrailing){ Button(action:{self.Setting = true}) { HStack { Image(systemName: "gear").foregroundColor(.white) } } .sheet(isPresented: self.$Setting){ NavigationView { NewItem( userData: userData) .navigationBarItems(trailing:Button(action: { self.Setting = false }){ Text("Done") } ) } } } } .background(Color(red: 203/255, green: 237/255, blue: 207/255)) } detail: { ZStack { Text("") } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(red: 220/255, green: 247/255, blue: 234/255)) } .searchable(text: $searchText) } }
1
1
1.1k
Jul ’23
Error: No exact matches in reference to static method 'buildExpression'
Getting the error: "No exact matches in reference to static method 'buildExpression'" in the following code: var categoryNames: [String] = [] ForEach(categories, id: \.self) { category in if let categoryName = category.cCategoryName { categoryNames.append(categoryName) } } Note that categories is a variable pointing to my coredata entity and cCategoryName is an attribute of that entity. I don't have any methods in any of my code called "buildExpression". Is this a bug? Thanks!
3
0
12k
Oct ’23
NavigationSplitView hide sidebar toggle button
I'm trying to implement the same UI used by the Settings app on iPad: a split view with two columns that are visible at all times. This code produces the layout i want, but I would like to hide the "toggle sidebar visibility" button that the system introduces. Is there a SwiftUI API I can use to hide this button? Maybe an alternate way to setup views that tells the system that the button is not necessary? struct SomeView: View { var body: some View { NavigationSplitView( columnVisibility: .constant(.all), sidebar: { Text("sidebar") }, detail: { Text("detail") } ) .navigationSplitViewStyle(.balanced) } }
4
3
5.1k
Nov ’23
NO ANIMATIONS in NavigationStack or NavigationSplitView
I'm building a macOS app using SwiftUI and I recently updated to xcode 14.3. Since then I've been debugging why none of my animations were working, it turned out that the NavigationSplitView or NavigationStack are somehow interfering with all the animations from withAnimation to .transition() and everything in between. Is anyone else experiencing this, knows a work around or knows why this is happening?
9
8
5.5k
3w
Potential SwiftUI Bug. Sheets with multiple detents appear to not deinitalise correctly.
As per the title, I've drafted up a bug report but just wanted to sanity check this is not intended behavior before I sent off the report. Issue: If you present a sheet in SwiftUI using the .sheet(isPresented: ) and have multiple presentation detents on the view such as .presentationDetents([.medium, .large]) the view being presented appears to not correctly deinitialise when the view is dismissed. I have a short sample view which can easily demonstrate this. import SwiftUI struct ContentView: View { @State var showSheet = false var body: some View { Button("Show Sheet") { showSheet = true } .sheet(isPresented: $showSheet) { DetailView() // With a single detent, the below class prints "this is denit". .presentationDetents([.medium]) // When multiple detents are specified the detail view appears to not deinit properly. // .presentationDetents([.medium, .large]) } } } struct DetailView: View { let deinitPrinter = DeinitPrinter() var body: some View { Text("foobar") } } final class DeinitPrinter { init() { print("this is init") } deinit { print("this is deinit") } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } If you run this code with just the .presentationDetents([.medium]) you get the expected behavior of the console printing: this is init this is deinit every time you open and close the sheet. However if you comment out .presentationDetents([.medium]) and uncomment out .presentationDetents([.medium, .large]) you only get this every time you open and close the sheet this is init Just wondering if this is expected behaviour and if it is, why? If not I can happily press submit on my bug report. Cheers.
3
9
1.4k
Sep ’23
Why isn't the View protocol @MainActor?
Hi, It is known that if a SwiftUI view contains an @ObservedObject or @StateObject property, the View will inherit @MainActor isolation from the property wrappers. Similarly, the body view-builder is also marked @MainActor. What I'm wondering is why the whole SwiftUI View protocol isn't marked @MainActor. It seems to be a deliberate decision, but AFAICT it would make a lot of sense for all data and operations defined in a view to have main-actor isolation unless marked nonisolated. I'm currently adding @MainActor annotations to an existing codebase, and it's a bit awkward that some views automatically gain this attribute one way or another, while others need it explicitly applied. Is there a rationale that can be shared, or is this something which may be revised in future versions of the framework?
1
6
1.3k
Jun ’24
Embedding a NavigationStack within the detail view of a NavigationSplitView
I'm using a two column NavigationSplitView, where the view passed for the detail column is the root of a NavigationStack. The navigation works as expected, but the navigationTitle and toolbar elements of the detail view are very slightly delayed when the view appears on iOS, such that they 'pop' in rather than smoothly animating like normal. Returning to the root of the view from views higher in this stack animates as expected. Has anyone seen anything like this before? Thanks!
6
0
1.7k
Oct ’23
tvOS/SwiftUI: toolbar item steals focus
I'm trying to add a brand logo to a SwiftUI tvOS interface. The main UI is a TabView. Focus works fine until I try to add a ToolbarItem. Once I do that it seems to steal focus and my TabView becomes unusable. Here's a simple example that demonstrates the problem: struct TestView: View { var body: some View { NavigationView { TabView { Text("Screen One") .tabItem({ Text("One") }) Text("Screen Two") .tabItem({ Text("Two") }) Text("Screen Three") .tabItem({ Text("Three") }) } .toolbar { ToolbarItem(placement: .navigationBarLeading) { Image(systemName: "house.fill") } } } } } How can I keep focus from getting messed up? Should I not be using the toolbar to add the logo? It looks like just adding toolbar causes a UINavigationBar to be drawn on top of the tab bar, which is why it isn't getting focus. Still not sure how to fix it though...
2
0
1k
Sep ’23
CloudKit Stopped Syncing after adding new Entities
Can someone please shed some light? I have an app that uses Core Data and CloudKit, up until the last version, I was able to sync data between devices but now after I added two new Entities for some reason it stopped syncing between devices. Here is how I did the change: Created a new Core Data container. Added the new Entities and their Attributes Tested the new Entities locally to be able to send the new schema to CloudKit. Went to CloudKit and made sure that the new Entities and Attributes were reflected on the Developent database. Deploy Schema Cahnges. Went to the Production database to make sure the new schema was deployed; and it was, both databases look the same. Testing: Tested in the simulator and with a real device and everything syncs, even the new Entities. If I download the app from the App Store on two different devices they do NOT sync. Based on the procedure I'm describing above, is there any important step I may have missed when doing the migration? I'm not sure if this is related to the syncing issue but after testing a few times, I no longer can turn the iCloud on, I get the following message when I try to turn iCloud Sync On. CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:]: <NSCloudKitMirroringDelegate: 0x282c488c0> - resetting internal state after error: Error Domain=NSCocoaErrorDomain Code=134410 "CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process." UserInfo={NSURL=file:///var/mobile/Containers/Data/Application/73F19BC7-4538-4098-85C7-484B36192CF3/Library/Application%20Support/CoreDataContainer.sqlite, NSLocalizedFailureReason=CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process., NSUnderlyingException=Illegal attempt to register a second handler for activity identifier com.apple.coredata.cloudkit.activity.setup.8D4C04F6-8040-445A-9447-E5646484521} Any idea of what could be wrong and preventing the devices from syncing? Any idea or suggestion is welcome. Thanks
3
0
1.9k
3w
ActionClassifier in SwiftUI App
Hello, I am reaching out for some assistance regarding integrating a CoreML action classifier into a SwiftUI app. Specifically, I am trying to implement this classifier to work with the live camera of the device. I have been doing some research, but unfortunately, I have not been able to find any relevant information on this topic. I was wondering if you could provide me with any examples, resources, or information that could help me achieve this integration? Any guidance you can offer would be greatly appreciated. Thank you in advance for your help and support.
1
0
932
Aug ’23
SwiftUI ToolbarItem Constraints Error
In this simple Hello World app (Xcode 14.3, iOS 14.4.1), adding a Toolbar item above the keyboard leads to constraints errors in the log when you tap the TextField. It does not seem to lead to any obvious errors in the UI. Anyone have ideas on how to work around this? struct ContentView: View { @State private var foodName: String = "" var body: some View { VStack { TextField("test", text: $foodName) } .padding() .toolbar { ToolbarItem(placement: .keyboard) { Text("Test") } } } } [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x28137d2c0 h=--& v=--& _UIToolbarContentView:0x143609e30.width == 0 (active)>", "<NSLayoutConstraint:0x2813708c0 H:|-(16)-[_UIButtonBarStackView:0x143608ab0] (active, names: '|':_UIToolbarContentView:0x143609e30 )>", "<NSLayoutConstraint:0x281370910 H:[_UIButtonBarStackView:0x143608ab0]-(16)-| (active, names: '|':_UIToolbarContentView:0x143609e30 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x281370910 H:[_UIButtonBarStackView:0x143608ab0]-(16)-| (active, names: '|':_UIToolbarContentView:0x143609e30 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
4
4
1.2k
Oct ’23
SwiftUI Charts AxisValueLabel disappears when using centered: true
Hi there, When using the AxisValueLabel in Swift Charts, the moment you add centered: true, the month or day on the right disappears. This has been a bug for over five months since I looked through other developer forums and they had the same issue. AxisValueLabel(format: .dateTime.weekday(), centered: true) leads to the following view: Now if we remove the centered: true, saturday will appear. It is probably a spacing issue, but since these are modifiers provided by Apple, it should do it correctly, right? If I am missing something and this is by desing, please enlighten me. Best Til
1
0
1.1k
Aug ’23
Memoization in SwiftUI views
I have a view which shows some data based on a complex calculation. Let's say I need to parse some input string and transform it in some way. private func someComplexCalculation(_ input: String) -> String { // ... } The most naive approach would be to perform this in the view's body: struct MyView: View { let input: String var body: some View { Text(someComplexCalculation(input)) } } But of course, we want to keep body nice and fast because SwiftUI may call it very often. The text to be displayed will be constant for a particular view, in a particular place in the hierarchy (barring some major events such as locale changes, which can basically change the entire UI anyway). So the next idea would be to hoist the calculation out of body in to the view's initialiser: struct MyView: View { let value: String init(_ value: String) { self.value = someComplexCalculation(value) } var body: some View { Text(value) } } Except that this view's initialiser will be called in the body of its parent, so this isn't really much of a win at all. So the next idea is that we need to associate the cached data with the underlying view itself somehow. From what we are told about SwiftUI, that's what @State does. struct MyView: View { @State var value: String init(_ value: String) { self._value = State(initialValue: someComplexCalculation(value)) } var body: some View { Text(value) } } Except... apparently this is not recommended because SwiftUI won't honour the value set in the initialiser. That's kind of okay for my purposes - the contents won't change, and every view with the same identity (place in the hierarchy) will be provided the same input. The real problem emerges when we look at the documentation for @State. Its initialiser takes a value directly, so we're still going to perform this expensive calculation every time; we'll just discard the value immediately afterwards and take one which the framework memoised. Which brings me on to my final approach - @StateObject. Unlike @State, its initialiser takes an autoclosure, so we won't recompute the value every time. But it should still be stored in a way that is bound to the underlying view, thereby giving me a place to stash memoised values. struct MyView: View { final class Cache { var transformed: String init(input: String) { self.transformed = someComplexCalculation(value) } } @StateObject var cache: Cache init(_ value: String) { self._cache = StateObject(wrappedValue: Cache(input: value)) } var body: some View { Text(cache.transformed) } } I haven't been able to find much in the way of others online using @StateObject for this purpose, so I'd like to ask - is there some other solution I'm overlooking? Is this considered a misuse of @StateObject for some reason? The documentation for the StateObject initialiser says: Initialize using external data If the initial state of a state object depends on external data, you can call this initializer directly. However, use caution when doing this, because SwiftUI only initializes the object once during the lifetime of the view — even if you call the state object initializer more than once — which might result in unexpected behavior. Which seems fine. This seems like exactly what I want.
2
0
1.1k
Jun ’24