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

NSTableView doesn't show new data
I have a NSTableView under a NSViewRepresentable and I'm trying to add a new row when the + button is clicked. With the code below, the ForEach statement is updated when the data is added to the state variable, but the table view doesn't show the new element. Why is that? import PlaygroundSupport import SwiftUI struct TV: NSViewRepresentable {   @Binding var students: Array&lt;String&gt;       func makeNSView(context: Context) -> NSScrollView {     let sv = NSScrollView()     let tv = NSTableView()     sv.documentView = tv     tv.gridStyleMask = .solidHorizontalGridLineMask     tv.usesAlternatingRowBackgroundColors = true//     tv.allowsMultipleSelection = true     let col = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "Name"))     col.title = "Name"     _ = tv.addTableColumn(col)           _ = tv.delegate = context.coordinator     tv.dataSource = context.coordinator     return sv   }   func updateNSView(_ nsView: NSScrollView, context: Context) {     (nsView.documentView as! NSTableView).reloadData()   }   func makeCoordinator() -> Coordinator {     Coordinator(self, students: self._students)   }         class Coordinator: NSObject, NSTableViewDelegate, NSTableViewDataSource {     var parent: TV     @Binding var students: Array&lt;String&gt;     init(_ parent: TV, students: Binding&lt;Array<String&gt;>) {       self.parent = parent       self._students = students     }     func numberOfRows(in tableView: NSTableView) -> Int {       return students.count     }     func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {       print(students[row])       return students[row]     }     func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {       return true     }     func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) {       self.students[row] = object as! String     }   } } struct view: View {   @State var students = ["John", "Mary", "Bob"]   @State var minusDisabled: Bool = true       var body: some View {     Group {       VStack(alignment: .leading) {         Text("Test")         TV(students: self.$students).frame(width: 400, height: 300)         HStack {           Button(action: {             self.students.append("New Row")           }) {             Text("+")             }.buttonStyle(BorderedButtonStyle())           Button(action: {           }) {             Text("-")           }.buttonStyle(BorderedButtonStyle())           .disabled(self.minusDisabled)         }       }.fixedSize()       ForEach(self.students, id: \.self) { student in         Text(student)       }     }   } } PlaygroundPage.current.setLiveView(view().frame(width: 500, height: 800))
1
0
764
Aug ’23
Nested ZStack fails to space contained views properly - SwiftUI bug?
I have a ZStack with two nested views. They are both the same type, RowView, and each RowView has another ZStack and a Text. Both of these RowViews have the same height for some reason. And when I replace the RowView ZStack with just a Text, it works correctly. import SwiftUI struct ContentView: View {     var body: some View {         ScrollView { &amp;#9;&amp;#9; // remove this ZStack and things work with the other nested ZStacks             ZStack {                 Rectangle()                     .foregroundColor(.blue)                     .shadow(radius: 5, x: 5, y: 5)                                  VStack {                     // Two independent RowViews:                                          RowView(title: "Some really long text for some stuff lollola really long text for some stuff lollola")                                          RowView(title: "and more")                 }             }             .padding()         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } } struct RowView: View {     @State var title: String          let boxSize: CGFloat = 40          var body: some View {         HStack(alignment: .top, spacing: nil) {             Rectangle()                 .foregroundColor(.orange)                 .frame(minWidth: boxSize,                        maxWidth: boxSize,                        minHeight: boxSize,                        maxHeight: boxSize)                 .padding(5)                          // this has each RowView set its own height correctly //            Text(title) //                .multilineTextAlignment(.leading) //                .padding(5)             // this forces both RowViews to have the same height, even though they are separate from each other             ZStack {                 Rectangle()                     .foregroundColor(.gray)                                  Text(title)                     .multilineTextAlignment(.leading)                     .padding(5)             }             .padding(5)             // this also forces both RowViews to have the same height //            Rectangle() //                .foregroundColor(.gray) //                .overlay(Text(title).padding()) //                .padding(5)         }     } } It seems strange that both independent RowViews will end up having the same height. Read the release notes and didn't see mention of this being a possible bug. Copy pasta and see the results if you'd like. Notice the Gray ZStack containers are all almost the same height? Make the test of the first row even longer. Notice how the second one increases it's height? Is this a bug,? Are ZStacks never supposed to be nested?
2
0
2.4k
Aug ’23
Is it me or is SwiftUI on macOS just awful?
I have recently created a pure (admittedly simple) SwiftUI app for iOS/iPad. Yes there are bugs and limitations I've had to face but eventually with a certain amount of compromise and without resorting to UIViewRepresentable, it works adequately. Great, I thought, how hard can it be to create a macOS version of the same app? Take TextField (swiftUI) views which my app depends on a lot, the issues I have found have been numerous... TextField does not appear to update the Binded variable after each character is typed in. You have to hit the return key for it to register. Totally different functionality. Placeholder text shifts up a few pixels when it gets keyboard focus. The rectangle where the text is typed needs to be taller holding the text, currently it looks squashed. Manually adding a ‘clear text’ button on top of the TextField (at the right) appears not to to be active when the cursor is over it (most of the time) Lots of missing autocapitalisation type functionality is missing. I could go back to a NSViewRepesentable solution of the TextField but that negates the use of 'supported' SwiftUI features. Has this half baked feature been pushed out there as a 'tick in the box' option or is Apple genuinely happy with their solution? Anyhow, I thought let's do a MacCatalyst version of my App instead. But we get a TabView looking like a iPad/iPhone App, there is no option to make it look more mac like AFAIS without abandoning TabView itself! Then there's the complication of making my Core Data App work as a 'Document Based' app with the new DocumentGroup/Scene solution.... how does NSPersistentDocument work in such scenarios? The documentation is vague at best, or simply not supported without a lot of workarounds. Just these few things make me feel we are being hyped with solutions which are far too premature for any real world work on macOS at the moment. What potential SwiftUI/macOS blockers have you encountered?
6
3
2.5k
Sep ’23
.sheet no longer dismissable in WatchOS 7?
In WatchOS 6 a presented .sheet could be dismissed by swiping down or tapping on the navigationBarTitle. In the WatchOS 7 beta, presented sheets are no longer dismissible by either method...forcing the addition of a button to dismiss. It appears as if .sheet is now acting as .fullScreenCover within WatchOS 7. Anyone else running into this? Wondering if this is now expected behavior on WatchOS or if it's a bug...
7
0
2.7k
Oct ’23
SwiftUI Scene with a single window on macOS
Is it possible to only allow a single window instance on macOS? WindowGroup/DocumentGroup allow the user to create multiple instances of a window. I'd like to only allow one, for an Onboarding sequence. I've checked the Scene documentation - https://developer.apple.com/documentation/swiftui/scene, and it appears the only types conforming to the Scene protocol are WindowGroup, DocumentGroup and Settings. How can I create a single Window in a SwiftUI App? An example use case: struct TutorialScene: Scene {   var body: some Scene { &#9;// I don't want to allow multiple windows of this Scene! &#9;WindowGroup { &#9;&#9;TutorialView() &#9;}&#9; }
6
0
3.8k
1d
SwiftUI presentationMode dismiss not work on specific case
I am presenting a sheet using the view modifier .sheet(item: ...) if the view you are presenting is wrap inside another view which only add a navigation view let's say I have a view called ViewB with a dismiss button which called the presentation mode dismiss, that works let' say I have another view called ViewBWithNavigationView where it's calling ViewB inside the NavigationView and it also calling dismiss on the cancel button the result of this is that the presentation mode dismiss will only works for the first view B the cancel button, it will no close the view if you click the button inside the view struct ViewBInsideNavigationView: View {       @Environment(\.presentationMode) var presentationMode   var body: some View {     NavigationView {       ViewB()         .navigationBarTitle("View B", displayMode: .inline)         .navigationBarItems(leading: Button("Cancel") {           self.presentationMode.wrappedValue.dismiss()         })     }   } } the call to self.presentationMode.wrappedValue.dismiss() inside ViewB is not trigger and the view is not dismiss thanks
12
0
15k
Oct ’23
How should I access @AppStorage and @SceneStorage values outside of views?
The two property wrappers @AppStorage and @SceneStorage are great because you can simply redeclare a property in multiple views to share the value and automatically update other views. But how should I access those same values outside of views? I have helper functions which are used in multiple views and which change behaviour based on those stored properties. I believe I could use the old NSUserDefaults.standard to reference the @AppStorage values, but is that the "right" way to do it, and how do I access @SceneStorage values?
8
2
8.6k
Nov ’23
Swiftui Custom Fonts not showing
Hello, My Custom fonts are not showing in SwiftUI. I am all up to date on all of my software and I have added my TTF's to a fonts folder in my collection. I also added the "Fonts provided by application" array type to my info.plist and the fonts as elements. Here is my code. I have no idea what I'm doing wrong. Is there a bug in the latest version of Swiftui? Text("Hello World") &#9;&#9;&#9;.font(.custom("VervelleScript-lgxR0", size: 36))
6
1
5.8k
4d
Custom back button with SwiftUI
Hello, I'm trying to remove the current back button behavior in a navigation view and instead have a simple arrow. Disabling the button with navigationBarBackButtonHidden and then adding my own with navigationBarItems works, but then I lose the swipe gesture to go back. I could try to rebuild this swipe gesture, but that seems hard to get the same feel, and it will most likely break often. Is there something simpler ? I'd be satisfied with just removing the text of the back button and keeping only the <. Thanks
10
2
11k
Oct ’23
Widget SwiftUI previews failure when adding a dependency
Repro steps: Create new project Create WidgetKit extension (verify that previews work) Create dummy framework (verify that previews still work) Link dummy framework to the widget extension At that point, preview stops working with the following error: "RemoteHumanReadableError ProcessError: Failed to launch widget extension: The operation couldn’t be completed. (CHSErrorDomain error 1050.)" What can I do to make this work?
10
1
5.8k
Sep ’23
SwiftUI: WidgetKit Gradient Bug
I'm trying to make a gradient for Widgets and using 2 blue colors (#0091f1 and #0054f3) but the Widget background looks green. I've set up colors via Assets.xcassets and then using the following code: LinearGradient(gradient: Gradient(colors: [Color("color1"), Color("color2")]), startPoint: .top, endPoint: .bottom) For the common iOS target the gradient looks right (blue) and for the Widgets extension it's green. Could you help me to figure out why this is happening? The link - https://github.com/maximbilan/SwiftUI-WidgetKit-Gradient-Issue to the example with screenshots.
4
0
2k
Aug ’23
SwiftUI negative kerning cuts off font
Hey there! Got a question about font kerning: When adding a negative kerning to a text (changes via user input) the last character sometimes gets cut off: dropbox.com/s/49ucdzk8m4k61sj/fontproblem1.png?dl=0 dropbox.com/s/vmklvxp510wjeak/fontproblem2.png?dl=0 What i do is the following: Text("\(pos, specifier: "%.1f")") &#9;.font(.system(size: 100,design: .serif)) &#9;.fontWeight(.bold) &#9;.kerning(-5) When i remove the kerning it works, but as i understood the kerning keeps the letters as they are? Is there an alternative way of doing it?
2
0
851
Apr ’24
SwiftUI custom picker view?
I'm trying to create a custom Picker similar to the one in the Reminders app where users can select colors and icons for a list of reminders. I currently have this: struct CustomPickerStyle: PickerStyle {     static func _makeView<SelectionValue>(value: _GraphValue<_PickerValue<CustomPickerStyle, SelectionValue>>, inputs: _ViewInputs) -> _ViewOutputs where SelectionValue : Hashable {     }     static func _makeViewList<SelectionValue>(value: _GraphValue<_PickerValue<CustomPickerStyle, SelectionValue>>, inputs: _ViewListInputs) -> _ViewListOutputs where SelectionValue : Hashable {     } } These are automatically generated by Xcode. How should I deal with these methods? I could not find any documentation online for making a custom picker view... Thanks!
3
0
2.4k
Aug ’23
SwiftUI's onAppear() and onDisappear() called multiple times and inconsistently on iOS 14.1
I've come across some strange behavior with SwiftUI's onAppear() and onDisappear() events. I need to be able to reliably track when a view is visible to the user, disappears, and any other subsequent appear/disappear events (the use case is tracking impressions for mobile analytics). I was hoping to leverage the onAppear() and onDisappear() events associated with swiftUI views, but I'm not seeing consistent behavior when using those events. The behavior can change depending on view modifiers as well as the simulator on which I run the app. In the example code listed below, I would expect that when ItemListView2 appears, I would see the following printed out in the console: button init button appear And on the iPhone 8 simulator, I see exactly that. However, on an iPhone 12 simulator, I see: button init button appear button disappear button appear Things get even weirder when I enable the listStyle view modifier: button init button appear button disappear button appear button disappear button appear button appear The iPhone 8, however remains consistent and produces the expected result. I should also note that in no case, did the Button ever seem to disappear and re-appear to the eye. These inconsistencies are also not simulator only issues, i noticed them on devices as well. I need to reliably track these appear/disappear events. For example I'd need to know when a cell in a list appears (scrolled into view) or disappears (scrolled out of view) or when, say a user switches tabs. Has anyone else noticed this behavior? To me this seems like a bug in SwiftUI, but I'm not certain as I've not used SwiftUI enough to trust myself to discern a programmer error from an SDK error. If any of you have noticed this, did you find a good work-around / fix? Thanks, Norm // Sample code referenced in explanation // Using Xcode Version 12.1 (12A7403) and iOS 14.1 for all simulators import SwiftUI struct ItemListView2: View { &#9;&#9;let items = ["Cell 1", "Cell 2", "Cell 3", "Cell 4"] &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;ListingView(items: items) &#9;&#9;} } private struct ListingView: View { &#9;&#9;let items: [String] &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;List { &#9;&#9;&#9;&#9;&#9;&#9;Section( &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;footer: &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;FooterButton() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onAppear { print("button appear") } &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onDisappear { print("button disappear") } &#9;&#9;&#9;&#9;&#9;&#9;) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;ForEach(items) { Text($0) } &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} //&#9;&#9;&#9;.listStyle(GroupedListStyle()) &#9;&#9;} } private struct FooterButton: View { &#9;&#9;init() { &#9;&#9;&#9;&#9;print("button init") &#9;&#9;} &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;Button(action: {}) { Text("Button")&#9;} &#9;&#9;} }
8
1
10k
Aug ’23
Why does same code work differently within SwiftUI Life Cycle and UIKit App Delegate Life Cycle?
Introduction I created a simple app to test enabling Sign In with Google using Observable Objects in a SwiftUI Application. However, the app only functions properly (displaying the signed in user's name and email) with a UIKit App Delegate Life Cycle. The code of the App file for the SwiftUI life cycle and that of the app delegate and scene delegate files of the UIKit App Delegate life cycle should function identical; however, they do not. Project Code SwiftUI Lift Cycle AppDelegate import UIKit import SwiftUI import GoogleSignIn class AppDelegate: NSObject, UIApplicationDelegate { /* GoogleDelegate() is the observable object */ let googleDelegate = GoogleDelegate() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { GIDSignIn.sharedInstance()?.clientID = "CLIENT_ID" GIDSignIn.sharedInstance()?.delegate = googleDelegate return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return GIDSignIn.sharedInstance().handle(url) } } App @main struct WidgiTubeApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var window: UIWindow? { guard let scene = UIApplication.shared.connectedScenes.first, let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate, let window = windowSceneDelegate.window else {             return nil } return window } @Environment(\.scenePhase) private var scenePhase let googleDelegate = (UIApplication.shared.delegate as! AppDelegate).googleDelegate var body: some Scene { WindowGroup { GoogleSignInView() .environmentObject(googleDelegate) }.onChange(of: scenePhase) { (phase) in switch phase { case .active: GIDSignIn.sharedInstance().presentingViewController = window?.rootViewController window?.makeKeyAndVisible() case .inactive: case .background: default: } } } } Using the SwiftUI Life Cycle the User Is signed in; however, the information does not update in the SwiftUI view. (The view is identical between the SwiftUI Life Cycle and UIKit Application Delegate Life Cycle.) UIKit Application Delegate Life Cycle App Delegate DidFinishLaunchingWithOptions GIDSignIn.sharedInstance().clientID = "CLIENT_ID" GIDSignIn.sharedInstance().delegate = googleDelegate return true OpenURL return GIDSignIn.sharedInstance().handle(url) Scene Delegate SceneWillConnectTo let googleDelegate = (UIApplication.shared.delegate as! AppDelegate).googleDelegate let contentView = ContentView().environmentObject(googleDelegate) if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) GIDSignIn.sharedInstance()?.presentingViewController = window.rootViewController self.window = window window.makeKeyAndVisible() } Conclusion Due to this, I have identified that there must be some issue that occurs when adapting the UIKit App Delegate code to the SwiftUI App Code. However, I cannot identify what the issue between the two life cycles is. It is my understanding that anything possible with the UIKit Delegate life cycle should theoretically be possible with SwiftUI. In the mean time, of course, there is no issue continuing with the UIKit Delegate; however, I was hoping to create a SwiftUI app. If anyone could help me identify where the issue lays between these two different life cycles, I would greatly appreciate it. Thanks!
1
0
1.4k
5d
SwiftUI Toolbar… bug?
Hi everyone! I recently noticed a strange behaviour with the new SwiftUI Toolbar. I have an app with only 2 views: a ContentView and a DetailView. My goal is to have a different toolbar in both. ContentView: struct ContentView: View {     @State var isFavorite = false     var body: some View {         NavigationView {             VStack {                 Image(systemName: isFavorite ? "star.fill" : "star")                 NavigationLink(destination: DetailView(isFavorite: $isFavorite)) {                     Text("Go")                 }             }             .navigationTitle("ContentView")             .toolbar() {                 ToolbarItem(placement: .bottomBar) {                     Text("This is my ContentView")                 }             }         }     } } DetailView: struct DetailView: View {     @Binding var isFavorite: Bool     var body: some View {         Button("Tap me!") {             isFavorite.toggle()         }         .navigationTitle("DetailView")         .toolbar() {             ToolbarItem(placement: .bottomBar) {                 Text("This is my DetailView")             }             ToolbarItem(placement: .navigationBarTrailing) {                 Image(systemName: isFavorite ? "star.fill" : "star")             }         }     } } When I toggle the @Binding property in the DetailView, the toolbar is replaced by another empty toolbar appearing from nowhere. Am I doing something wrong?
7
0
5.5k
Aug ’23