What's new in SwiftUI

RSS for tag

Discuss the WWDC21 session What's new in SwiftUI.

Posts under wwdc21-10018 tag

50 Posts

Post

Replies

Boosts

Views

Activity

Xcode 13, automatically refresh canvas does not work
[Required] Xcode 13 pod installed : 'QImageDownloader' 'QImageDownloader/Rx' 'RealmSwift' 'SwiftyRSA' 'BDGhostover' 'Charts' 'ComScore' 'Gifu' 'GoogleAnalytics' 'Google-Mobile-Ads-SDK',  'GoogleMobileAdsMediation 'Firebase' 'FirebaseMessaging' 'Firebase/Analytics' 'Firebase/Crashlytics' 'Firebase/DynamicLinks' 'Firebase/RemoteConfig' 'ImageViewer.swift' 'lottie-ios' 'OguryAds', '2.5.0' 'OguryChoiceManager', '3. 'RealmSwift' 'RxAnimated' 'RxAppState' 'RxCocoa' 'RxRealm' 'RxSwift', '~> 5' 'RxDataSources' 'SwiftyStoreKit' 'XCoordinator' 'XCoordinator/RxSwift' When I try to use swiftUI file the preview does not work at all. I need to uncheck the automatically refresh canvas in the editor. previews.txt
1
0
1.7k
Dec ’21
How to set the context menu for the header and each row of the Table component ?
I want to use the Table component to achieve the following functions Right click the column header to pop up context menu Right click each row to pop up context menu I found that TableColumn and TableRow objects are not of type view. Setting contextMenu is not supported. I can set the ContextMenu on the cell in the following ways, but it only works inside the cell, and clicking on the blank part does not take effect. TableColumn("Given Name", value: \.givenName) { person in Text(person.givenName) .contextMenu(menuItems: { Button { } label: { Text("New Order") } }) } How to set independent context menus on rows and column headers?
0
0
495
Nov ’21
How to show SF-symbols icons in SwiftUI TabView in macOS Monterey Version 12.0
I try to use TabView with tabItems that include SF-Symbols 3- Icons. To get started, I created a simple SwiftUI from the Apple SwiftUI example. I tried several variations : symbols with fill and without fill. tabItems with Stack, and without, with Label or Text and Image  ` TabView {             Text("The First Tab")                 .tabItem {                     VStack {                         Image(systemName: "1.square.fill")                         Text("First")                     }                 }             Text("The First Tab - 2")                 .tabItem {                     VStack {                         Image(systemName: "1.square")                         Text("First - 2")                     }                 }             Text("Another Tab")                 .tabItem {                     Label("second -2", systemImage: "2.square.fill")                 }             Text("Another Tab - 2")                 .tabItem {                     Label("second", systemImage: "2.square")                 }             Text("The Last Tab")                 .tabItem {                         Image(systemName: "3.square")                         Text("Third")                 }             Text("The Last Tab - 2")                 .tabItem {                         Image(systemName: "3.square.fill")                         Text("Third -2")                 }         }` The same code works when used in a preferences SwiftUI View. Is there any further prerequisite to display Icons on tabbars?
0
0
1.2k
Nov ’21
Picker under the search bar
Dear all, I want to add a Picker view under the search bar similarly as seen on the Files app: I would be happy with one of the two options - 1) to have a picker view to be visible under the search bar all the time (ie. even when the search bar is not activated), 2) to have the picker view to be visible when search bar is active. I tried to implement this by using the toolbar modifier but without luck. NavigationView {     List {         ...     }     .searchable(text: $searchText)     .toolbar {         ToolbarItem {             Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented)         }     } } I have also tried the workaround by adding the Picker view within the List/Form but in this case the Picker view disappears when the user scrolls the list down.     List {         Section {             Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented)         }         ...     }     .searchable(text: $searchText) } One last thing I tried was to put the picker view within the search bar’s suggestions parameter. This however, obscures the search results under the suggestions view.     List {         ...     }     .searchable(text: $searchText), suggestions: Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented) }) } Any ideas?
0
0
1.9k
Oct ’21
How to give default value to TableColumn in Table
I have this sample code: struct Item: Identifiable { var id = UUID() var name: String? } struct ItemTable: View { let items: [Item] var body: some View { Table(items) { TableColumn("Name", value: \.name) } } } I get the following error: Key path value type 'String?' cannot be converted to contextual type 'String' I can solve using \.name!, but I'd like to give a default value instead (something like \.name ?? "default"). How can I achieve this?
3
0
1.4k
Oct ’21
How to add a search bar to a list?
Hi guys, I try to use .searchable to add search bar to a list, see my code as below, but it doesn't work. How can I make it work? Somebody, please help me!!! import SwiftUI @available(iOS 15.0, *) struct ContentView: View {       var body: some View {     NavigationView {       TabView{         VStack{           List{             Text("aaa")             Text("bbb")             Text("ccc")           }           .searchable(text: .constant(""))         }         .tabItem({           Text("tab1")                     })         VStack{           Text("tab2")         }         .tabItem({           Text("tab2")                     })                 }             }         } } @available(iOS 15.0, *) struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
1
0
1.7k
Oct ’21
SwiftUI - View pop backs on button click automatically
I am working on a shopping app with firestore as a backend, where users add products to the cart.(Shop -> Product Category -> Product -> Add to cart). There is some weird behavior when the user clicks on the add to cart button. For the first time when the user clicks on Add to cart, the view automatically pops back to the Product category screen. Then if I click on any product category it goes to the product screen and pops back automatically. I am stuck with this issue for a couple of days, Please shed some light on what I am doing wrong. Thanks a ton. Product @DocumentID var id : String? var name : String? var price : String? var available : Bool = false var quantity : Int = 1 var category : String? enum CodingKeys: String, CodingKey { case id, name, price, category, available } } ProductViewModel @Published var productArray : [Product] = [] @Published var selectedProducts : [Product] = [] @Published var productTotal = ProductTotal(totalAmt: 0) @Published var productImgDict : [String : String] = [:] @Published var selectedProduct = Product() @Published var cartResponse : CartResponse? @Published var isCartRespReceived : Bool = false @Published var checkoutResponse : CheckOutResponse? @Published var isCheckOutResReceived : Bool = false var products : [Product] = [] var dummyProductLst : [Product] = [] var dummyCartItems : [Product] = [] var firestore = Firestore.firestore() var storageRef = Storage.storage() init(){ isCartRespReceived = false } func setSelectedProduct(product : Product) { selectedProducts.append(product) self.dummyCartItems.append(product) self.setDefaultProductQty(product: product) } func setDefaultProductQty(product : Product) { for index in self.selectedProducts.indices { if product.id == self.selectedProducts[index].id { //By default setting the quantity to 1 when adding a product self.selectedProducts[index].quantity = +1 }else{ print("not matched") } } } func getSelectedProduct() -> [Product] { return self.selectedProducts } func deleteProduct(index : IndexSet) { self.selectedProducts.remove(atOffsets: index) self.dummyCartItems.remove(atOffsets: index) } func getTotalAmount() -> ProductTotal { var totalAmt = 0; for item in self.selectedProducts { totalAmt = totalAmt + Int(item.price?.floatValue ?? 0) } return ProductTotal( totalAmt: totalAmt) } func setQuantity(index : Int, qty : Int = 1) { self.selectedProducts[index].quantity = qty } func setgetUpdatedPrice(index : Int, qty : Int, itemID : String = "") -> String { var calculatedAmt = 0 if let data = self.dummyCartItems.first(where: {$0.id == itemID}) { calculatedAmt = Int(data.price?.floatValue ?? 0) * qty self.selectedProducts[index].price = String(calculatedAmt) } else { // item could not be found } _ = getTotalAmount() print(calculatedAmt) return String(calculatedAmt) } } ProductGridView @EnvironmentObject var prodViewModel : ProductViewModel @EnvironmentObject var partialSheetManager : PartialSheetManager @Binding var showToast : Bool var product : Product var store : Store var body: some View { ZStack(alignment: Alignment(horizontal: .trailing, vertical: .top)){ VStack(alignment: .center, spacing: 10){ let imgURL = prodViewModel.productImgDict[product.id ?? ""] AnimatedImage(url: URL(string: imgURL ?? "")).resizable().frame(width: 110, height: 110).padding() HStack{ Text("₹\(product.price ?? "")") .foregroundColor(Color.theme.appColor) .font(.title2).bold() Spacer(minLength: 20) if product.available { Button(action: { if self.prodViewModel.getSelectedProduct().contains(where: { $0.id == product .id}){ //item found }else{ // not found in cart - add product to array if store.id == AppSettings.shared.getStoreID(){ prodViewModel.setSelectedProduct(product: product) showToast = true }else{ print("shop is different, you cannot add it") self.partialSheetManager.showPartialSheet { ChangeShopView(store: store, product: product) } } } }, label: { Image.init(systemName: "cart.badge.plus") .renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original)) .resizable() .frame(width: 32, height: 30) } ) }else{ } } HStack{ Text(product.name ?? "") .font(.title3) .multilineTextAlignment(.leading) .foregroundColor(Color.theme.textColor) Spacer() } } .overlay( Text( product.available ? "" : "NOT AVAILABLE") .foregroundColor(.white) .background(Color.red) .font(.caption) .clipShape(RoundedRectangle(cornerRadius: 4)) .padding(.horizontal) ,alignment: .center) .padding(.horizontal, 8) .frame(width : UIScreen.main.bounds.size.width/2.4) .background(Color.theme.cardColor) .cornerRadius( 6) .shadow(color: Color.black.opacity(0.2), radius:5, x:-5, y:5) } } } On clicking Add to cart button I am calling the setSelectedProduct method from ProductViewModel. In the console, am getting - Unable to present. Please file a bug.
0
0
712
Sep ’21
Error with: Binding, ForEach and TextField
I have been trying to use the new @Binding capabilities in SwiftUI but every time I make a ForEach and pass binding values, when the TextField changes, the keyboard unfocuses the Field. struct ContentView: View {     @State private var texts: [String] = ["Orange", "Apple"]          var body: some View {         NavigationView {             List {                 ForEach($texts, id: \.self) { $text in                     TextField("Fruit", text: $text)                 }             }             .navigationTitle("Fruit List")         }         .navigationViewStyle(.stack)     } } That is what I have tried, is there an error in my implementation or is it just a bug? My Mac: MacMini 2020 - M1 16GB Xcode 13.0 - (13A233) Project Built - for iOS 15
3
0
2.2k
Sep ’21
What happened to primaryAction in Menu?
According to WWDC video and documentation this code should work: Menu { Button(action: addCurrentTabToReadingList) { Label("Add to Reading List", systemImage: "eyeglasses") } Button(action: bookmarkAll) { Label("Add Bookmarks for All Tabs", systemImage: "book") } Button(action: show) { Label("Show All Bookmarks", systemImage: "books.vertical") } } label: { Label("Add Bookmark", systemImage: "book") } primaryAction: { addBookmark() } However when I try it, it throws an error: Extra argument in call for primaryAction any ideas? (latest beta MacOS, and latest Xcode)
4
0
687
Sep ’21
Using previewInterfaceOrientation results in runtime crash on iOS 14
Using Xcode 13 beta 2: In my SwiftUI preview code I add previewInterfaceOrientation like so: static var previews: some View { Group { Preview() #if swift(>=5.5) if #available(iOS 15.0, *) { Group { Preview() } .previewInterfaceOrientation(.landscapeRight) } #endif } } With this code and running on an iOS 14 device the app crashes immediately with dyld: Symbol not found: _$s7SwiftUI4ViewPAAE27previewInterfaceOrientationyQrAA0eF0VFQOMQ It would seem I can't use this handy interface orientation option in Previews until the app's minimum target is iOS 15. It seems like a bug in the framework because that symbol should be considered optional as it is surrounded by if #available.
2
0
1.2k
Sep ’21
Count the number of managed objects in a @SectionedFetchRequest
I am using a @SectionedFetchRequest with some success. This sectioned fetch request feeds data to a List(). I want to include a footer to the list that provides a count of the managed objects returned from the sectioned fetch request. Previously I have used .count. This still works but only returns the number of sections. A sectioned fetch request provides this result... SectionedFetchResults<String, CoreDataEntityClass> So how do I iterate through this unusual collection to determine a count?
1
0
1.6k
Sep ’21
SwiftUI, menu on macOS and the customization of the Label
Hey! It seems that Label used in the menu construction is wrapped in a system button and there is no way to change it– for example I’d like to display only the image and the image only (SFSymbol to be exact). With macOS 12 I can turn off the menu indicator or set the menuStyle (or even use custom style but the API is extremely limited; for example the Configuration doesn’t expose the label or body instances) but I can’t change the font size (of the button, not of the menu ofc) of the symbol… Does anyone figured it out?
0
0
1.2k
Aug ’21
SwiftUI: How to force a view presented in landscape mode?
I try UIDevice, but occurred error : let value = UIInterfaceOrientation.landscapeRight.rawValue UIDevice.current.setValue(value, forKey: "orientation") error: 2021-08-23 11:54:05.514193+0800 Spider-IOS[5696:1212060] [error] precondition failure: setting value during update: 805944 dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib AttributeGraph precondition failure: setting value during update: 805944.
0
0
650
Aug ’21
Xcode 13, automatically refresh canvas does not work
[Required] Xcode 13 pod installed : 'QImageDownloader' 'QImageDownloader/Rx' 'RealmSwift' 'SwiftyRSA' 'BDGhostover' 'Charts' 'ComScore' 'Gifu' 'GoogleAnalytics' 'Google-Mobile-Ads-SDK',  'GoogleMobileAdsMediation 'Firebase' 'FirebaseMessaging' 'Firebase/Analytics' 'Firebase/Crashlytics' 'Firebase/DynamicLinks' 'Firebase/RemoteConfig' 'ImageViewer.swift' 'lottie-ios' 'OguryAds', '2.5.0' 'OguryChoiceManager', '3. 'RealmSwift' 'RxAnimated' 'RxAppState' 'RxCocoa' 'RxRealm' 'RxSwift', '~> 5' 'RxDataSources' 'SwiftyStoreKit' 'XCoordinator' 'XCoordinator/RxSwift' When I try to use swiftUI file the preview does not work at all. I need to uncheck the automatically refresh canvas in the editor. previews.txt
Replies
1
Boosts
0
Views
1.7k
Activity
Dec ’21
How to use TableColumnBuilder and TableRowBuilder in SwiftUI 3.0 ?
Are there any relevant code examples to show how to use TableColumnBuilder and TableRowBuilder ?Thank you.
Replies
0
Boosts
0
Views
569
Activity
Nov ’21
How to drag the table header to reorder the columns?
Using NSTableView in Cocoa framework, it is easy to implement drag and drop sorting of table headers (not row sorting). But I didn't find out how to use the Table component in SwiftUI.
Replies
0
Boosts
0
Views
772
Activity
Nov ’21
How to set the context menu for the header and each row of the Table component ?
I want to use the Table component to achieve the following functions Right click the column header to pop up context menu Right click each row to pop up context menu I found that TableColumn and TableRow objects are not of type view. Setting contextMenu is not supported. I can set the ContextMenu on the cell in the following ways, but it only works inside the cell, and clicking on the blank part does not take effect. TableColumn("Given Name", value: \.givenName) { person in Text(person.givenName) .contextMenu(menuItems: { Button { } label: { Text("New Order") } }) } How to set independent context menus on rows and column headers?
Replies
0
Boosts
0
Views
495
Activity
Nov ’21
How does V/HStack update on Avatar Picker App on macOS?
Hello. How does V/HStack update on Avatar Picker App (The Contacts App) on macOS so smoothly? Can you share some source code, please?
Replies
0
Boosts
0
Views
833
Activity
Nov ’21
How to show SF-symbols icons in SwiftUI TabView in macOS Monterey Version 12.0
I try to use TabView with tabItems that include SF-Symbols 3- Icons. To get started, I created a simple SwiftUI from the Apple SwiftUI example. I tried several variations : symbols with fill and without fill. tabItems with Stack, and without, with Label or Text and Image  ` TabView {             Text("The First Tab")                 .tabItem {                     VStack {                         Image(systemName: "1.square.fill")                         Text("First")                     }                 }             Text("The First Tab - 2")                 .tabItem {                     VStack {                         Image(systemName: "1.square")                         Text("First - 2")                     }                 }             Text("Another Tab")                 .tabItem {                     Label("second -2", systemImage: "2.square.fill")                 }             Text("Another Tab - 2")                 .tabItem {                     Label("second", systemImage: "2.square")                 }             Text("The Last Tab")                 .tabItem {                         Image(systemName: "3.square")                         Text("Third")                 }             Text("The Last Tab - 2")                 .tabItem {                         Image(systemName: "3.square.fill")                         Text("Third -2")                 }         }` The same code works when used in a preferences SwiftUI View. Is there any further prerequisite to display Icons on tabbars?
Replies
0
Boosts
0
Views
1.2k
Activity
Nov ’21
Picker under the search bar
Dear all, I want to add a Picker view under the search bar similarly as seen on the Files app: I would be happy with one of the two options - 1) to have a picker view to be visible under the search bar all the time (ie. even when the search bar is not activated), 2) to have the picker view to be visible when search bar is active. I tried to implement this by using the toolbar modifier but without luck. NavigationView {     List {         ...     }     .searchable(text: $searchText)     .toolbar {         ToolbarItem {             Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented)         }     } } I have also tried the workaround by adding the Picker view within the List/Form but in this case the Picker view disappears when the user scrolls the list down.     List {         Section {             Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented)         }         ...     }     .searchable(text: $searchText) } One last thing I tried was to put the picker view within the search bar’s suggestions parameter. This however, obscures the search results under the suggestions view.     List {         ...     }     .searchable(text: $searchText), suggestions: Picker(selection: $selectedScope) {                 ...             } label: {                 ...             }             .pickerStyle(.segmented) }) } Any ideas?
Replies
0
Boosts
0
Views
1.9k
Activity
Oct ’21
How to give default value to TableColumn in Table
I have this sample code: struct Item: Identifiable { var id = UUID() var name: String? } struct ItemTable: View { let items: [Item] var body: some View { Table(items) { TableColumn("Name", value: \.name) } } } I get the following error: Key path value type 'String?' cannot be converted to contextual type 'String' I can solve using \.name!, but I'd like to give a default value instead (something like \.name ?? "default"). How can I achieve this?
Replies
3
Boosts
0
Views
1.4k
Activity
Oct ’21
textSelection(_:) too basic
This newly added feature, is a nice step in the right direction. Wondering if anyone has any idea how to actually allow the user to "select" the text as opposed to selecting all text and offering Copy/Share?
Replies
1
Boosts
0
Views
667
Activity
Oct ’21
SwiftUI books for beginners
just wondering what recommendations people have for books on swiftui for a beginner please?
Replies
1
Boosts
0
Views
652
Activity
Oct ’21
How to add a search bar to a list?
Hi guys, I try to use .searchable to add search bar to a list, see my code as below, but it doesn't work. How can I make it work? Somebody, please help me!!! import SwiftUI @available(iOS 15.0, *) struct ContentView: View {       var body: some View {     NavigationView {       TabView{         VStack{           List{             Text("aaa")             Text("bbb")             Text("ccc")           }           .searchable(text: .constant(""))         }         .tabItem({           Text("tab1")                     })         VStack{           Text("tab2")         }         .tabItem({           Text("tab2")                     })                 }             }         } } @available(iOS 15.0, *) struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
Replies
1
Boosts
0
Views
1.7k
Activity
Oct ’21
Cannot find ‘inputImage’ in scope
Hi everyone, I’m currently making an broadcast app for iPhone / iPad and mac, for this app I need an UIImagePickerController. But in my code get the following error: Cannot find ‘inputImage’ in scope. Can anyone help me? Thanks a lot, Robby
Replies
2
Boosts
0
Views
689
Activity
Oct ’21
My Navigation Bar Changes color after updating to Xcode13.
I am trying to use the solution provided by you but this doesn’t work. Can you please help me ?
Replies
2
Boosts
0
Views
466
Activity
Sep ’21
SwiftUI - View pop backs on button click automatically
I am working on a shopping app with firestore as a backend, where users add products to the cart.(Shop -> Product Category -> Product -> Add to cart). There is some weird behavior when the user clicks on the add to cart button. For the first time when the user clicks on Add to cart, the view automatically pops back to the Product category screen. Then if I click on any product category it goes to the product screen and pops back automatically. I am stuck with this issue for a couple of days, Please shed some light on what I am doing wrong. Thanks a ton. Product @DocumentID var id : String? var name : String? var price : String? var available : Bool = false var quantity : Int = 1 var category : String? enum CodingKeys: String, CodingKey { case id, name, price, category, available } } ProductViewModel @Published var productArray : [Product] = [] @Published var selectedProducts : [Product] = [] @Published var productTotal = ProductTotal(totalAmt: 0) @Published var productImgDict : [String : String] = [:] @Published var selectedProduct = Product() @Published var cartResponse : CartResponse? @Published var isCartRespReceived : Bool = false @Published var checkoutResponse : CheckOutResponse? @Published var isCheckOutResReceived : Bool = false var products : [Product] = [] var dummyProductLst : [Product] = [] var dummyCartItems : [Product] = [] var firestore = Firestore.firestore() var storageRef = Storage.storage() init(){ isCartRespReceived = false } func setSelectedProduct(product : Product) { selectedProducts.append(product) self.dummyCartItems.append(product) self.setDefaultProductQty(product: product) } func setDefaultProductQty(product : Product) { for index in self.selectedProducts.indices { if product.id == self.selectedProducts[index].id { //By default setting the quantity to 1 when adding a product self.selectedProducts[index].quantity = +1 }else{ print("not matched") } } } func getSelectedProduct() -> [Product] { return self.selectedProducts } func deleteProduct(index : IndexSet) { self.selectedProducts.remove(atOffsets: index) self.dummyCartItems.remove(atOffsets: index) } func getTotalAmount() -> ProductTotal { var totalAmt = 0; for item in self.selectedProducts { totalAmt = totalAmt + Int(item.price?.floatValue ?? 0) } return ProductTotal( totalAmt: totalAmt) } func setQuantity(index : Int, qty : Int = 1) { self.selectedProducts[index].quantity = qty } func setgetUpdatedPrice(index : Int, qty : Int, itemID : String = "") -> String { var calculatedAmt = 0 if let data = self.dummyCartItems.first(where: {$0.id == itemID}) { calculatedAmt = Int(data.price?.floatValue ?? 0) * qty self.selectedProducts[index].price = String(calculatedAmt) } else { // item could not be found } _ = getTotalAmount() print(calculatedAmt) return String(calculatedAmt) } } ProductGridView @EnvironmentObject var prodViewModel : ProductViewModel @EnvironmentObject var partialSheetManager : PartialSheetManager @Binding var showToast : Bool var product : Product var store : Store var body: some View { ZStack(alignment: Alignment(horizontal: .trailing, vertical: .top)){ VStack(alignment: .center, spacing: 10){ let imgURL = prodViewModel.productImgDict[product.id ?? ""] AnimatedImage(url: URL(string: imgURL ?? "")).resizable().frame(width: 110, height: 110).padding() HStack{ Text("₹\(product.price ?? "")") .foregroundColor(Color.theme.appColor) .font(.title2).bold() Spacer(minLength: 20) if product.available { Button(action: { if self.prodViewModel.getSelectedProduct().contains(where: { $0.id == product .id}){ //item found }else{ // not found in cart - add product to array if store.id == AppSettings.shared.getStoreID(){ prodViewModel.setSelectedProduct(product: product) showToast = true }else{ print("shop is different, you cannot add it") self.partialSheetManager.showPartialSheet { ChangeShopView(store: store, product: product) } } } }, label: { Image.init(systemName: "cart.badge.plus") .renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original)) .resizable() .frame(width: 32, height: 30) } ) }else{ } } HStack{ Text(product.name ?? "") .font(.title3) .multilineTextAlignment(.leading) .foregroundColor(Color.theme.textColor) Spacer() } } .overlay( Text( product.available ? "" : "NOT AVAILABLE") .foregroundColor(.white) .background(Color.red) .font(.caption) .clipShape(RoundedRectangle(cornerRadius: 4)) .padding(.horizontal) ,alignment: .center) .padding(.horizontal, 8) .frame(width : UIScreen.main.bounds.size.width/2.4) .background(Color.theme.cardColor) .cornerRadius( 6) .shadow(color: Color.black.opacity(0.2), radius:5, x:-5, y:5) } } } On clicking Add to cart button I am calling the setSelectedProduct method from ProductViewModel. In the console, am getting - Unable to present. Please file a bug.
Replies
0
Boosts
0
Views
712
Activity
Sep ’21
Error with: Binding, ForEach and TextField
I have been trying to use the new @Binding capabilities in SwiftUI but every time I make a ForEach and pass binding values, when the TextField changes, the keyboard unfocuses the Field. struct ContentView: View {     @State private var texts: [String] = ["Orange", "Apple"]          var body: some View {         NavigationView {             List {                 ForEach($texts, id: \.self) { $text in                     TextField("Fruit", text: $text)                 }             }             .navigationTitle("Fruit List")         }         .navigationViewStyle(.stack)     } } That is what I have tried, is there an error in my implementation or is it just a bug? My Mac: MacMini 2020 - M1 16GB Xcode 13.0 - (13A233) Project Built - for iOS 15
Replies
3
Boosts
0
Views
2.2k
Activity
Sep ’21
What happened to primaryAction in Menu?
According to WWDC video and documentation this code should work: Menu { Button(action: addCurrentTabToReadingList) { Label("Add to Reading List", systemImage: "eyeglasses") } Button(action: bookmarkAll) { Label("Add Bookmarks for All Tabs", systemImage: "book") } Button(action: show) { Label("Show All Bookmarks", systemImage: "books.vertical") } } label: { Label("Add Bookmark", systemImage: "book") } primaryAction: { addBookmark() } However when I try it, it throws an error: Extra argument in call for primaryAction any ideas? (latest beta MacOS, and latest Xcode)
Replies
4
Boosts
0
Views
687
Activity
Sep ’21
Using previewInterfaceOrientation results in runtime crash on iOS 14
Using Xcode 13 beta 2: In my SwiftUI preview code I add previewInterfaceOrientation like so: static var previews: some View { Group { Preview() #if swift(>=5.5) if #available(iOS 15.0, *) { Group { Preview() } .previewInterfaceOrientation(.landscapeRight) } #endif } } With this code and running on an iOS 14 device the app crashes immediately with dyld: Symbol not found: _$s7SwiftUI4ViewPAAE27previewInterfaceOrientationyQrAA0eF0VFQOMQ It would seem I can't use this handy interface orientation option in Previews until the app's minimum target is iOS 15. It seems like a bug in the framework because that symbol should be considered optional as it is surrounded by if #available.
Replies
2
Boosts
0
Views
1.2k
Activity
Sep ’21
Count the number of managed objects in a @SectionedFetchRequest
I am using a @SectionedFetchRequest with some success. This sectioned fetch request feeds data to a List(). I want to include a footer to the list that provides a count of the managed objects returned from the sectioned fetch request. Previously I have used .count. This still works but only returns the number of sections. A sectioned fetch request provides this result... SectionedFetchResults<String, CoreDataEntityClass> So how do I iterate through this unusual collection to determine a count?
Replies
1
Boosts
0
Views
1.6k
Activity
Sep ’21
SwiftUI, menu on macOS and the customization of the Label
Hey! It seems that Label used in the menu construction is wrapped in a system button and there is no way to change it– for example I’d like to display only the image and the image only (SFSymbol to be exact). With macOS 12 I can turn off the menu indicator or set the menuStyle (or even use custom style but the API is extremely limited; for example the Configuration doesn’t expose the label or body instances) but I can’t change the font size (of the button, not of the menu ofc) of the symbol… Does anyone figured it out?
Replies
0
Boosts
0
Views
1.2k
Activity
Aug ’21
SwiftUI: How to force a view presented in landscape mode?
I try UIDevice, but occurred error : let value = UIInterfaceOrientation.landscapeRight.rawValue UIDevice.current.setValue(value, forKey: "orientation") error: 2021-08-23 11:54:05.514193+0800 Spider-IOS[5696:1212060] [error] precondition failure: setting value during update: 805944 dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib AttributeGraph precondition failure: setting value during update: 805944.
Replies
0
Boosts
0
Views
650
Activity
Aug ’21