Post

Replies

Boosts

Views

Created

Will 2 environmentObject work?
Ive read posts where you can pass 2 .environmentObject() but what i noticed is that if i call object1.objectWillChange.send() , object2 also is affected is this normal? or supposedly only published properties of object1 only gets affected? discussion quwstion. thoughts?
1
0
430
Dec ’22
Suggestion How To Avoid Rebuilding View When Using EnvironmentObject
Hi, i wish to ask for suggestions. I am in a dilemna using an environment object. Please see code. struct ContentView: View {       @State var show = false   @StateObject var appData = AppData()   @StateObject var toolbarData = ToolbarData()   var body: some View {     NavigationStack(path: $appData.path) {       ZStack(alignment: .leading) {         VStack(spacing: 0) {           HStack {             Button(action: {               withAnimation(.default) {                 show.toggle()               }             }) {               Image(systemName: "line.3.horizontal")             }             Text("Home")             Spacer()             ToolbarView()             OverflowMenu()               .padding([.leading], Default.instance.PADDING_BETWEEN_MENU_ITEM)           }           .padding()           .foregroundColor(.primary)           .overlay(Rectangle().stroke(Color.primary.opacity(0.1), lineWidth: 1).shadow(radius: 3).edgesIgnoringSafeArea(.top))           MainContent(navigationManager: navigationManager)             .frame(maxWidth: .infinity, maxHeight: .infinity)         }          .environmentObject(toolbarData)         .background(Color.primary.opacity(self.show ? (self.dark ? 0.05 : 0.2) : 0))       }       .navigationBarHidden(true)     }     .navigationViewStyle(.stack)     .environmentObject(appData)   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } struct ToolbarView: View {       @Binding var toolbarData: ToolbarData       var body: some View {     HStack {       if let item = toolbarData.toolbarItem, item.visible {         Button {           item.action()         } label: {           if let iconLink = item.iconLink {             NavigationLink(destination: iconLink) {               Image(systemName: item.icon)             }           }           else {             Image(systemName: item.icon)           }         }         .disabled(item.disabled)         .opacity(item.opacity)         .padding([.leading, .trailing], Default.instance.PADDING_BETWEEN_MENU_ITEM)       }   } } final class ToolbarData: ObservableObject {   @Published var toolbarItem: ToolbarItemProperties? } final class ToolbarItemProperties {   var disabled = false } In the MainContent , my code runs this toolbarData.toolbarItemProperties.disabled = false I do not want MainContent to be rebuilt. Inside MainContent, I modify toolbarItemProperties (from an environment object). And i call objectWillChange.send(). Problem is, it will rebuild the ContentView widget including MainContent. What can be the correct approach to having to eb able to change the value of toolbarItemProperties and rebuild it but ignoring MainContent to rebuild again. Thoughts?
0
0
460
Dec ’22
Attempting to store bytes of data in CFPreferences/NSUserDefaults on this platform is invalid
I am not really sure what is the cause but this happens if i overwrite values. if i clear the app from scratch and store them all it works ok. Thoughts? my exact message is Attempting to store >= 4194304 bytes of data in CFPreferences/NSUserDefaults on this platform is invalid Description of keys being set: holocene_update: string value, approximate encoded size: 25 Description of keys already present: holocene: string value, approximate encoded size: 5216090 GMSMapsUserClientZwiebackCookie: string value, approximate encoded size: 175 GMSMapsUserCookie: data value, size: 48 kGMSServerVersionMetadataTrackerSavedServerVersionMetadataKey: data value, size: 30 holocene_update: string value, approximate encoded size: 25 com.google.Maps.GMSCoreLastVersion: string value, approximate encoded size: 6 cyclone_alert_last: string value, approximate encoded size: 5 com.google.Maps.GMSSDKLastVersion: string value, approximate encoded size: 5 GMSMapsUserClientCohort: string value, approximate encoded size: 4 kGMSMapsUserClientLegalCountry: string value, approximate encoded size: 2 ... Total keys: 12 - Average approximate value size: 434699 bytes 2022-12-19 17:49:08.777899+0800 PH Weather And Earthquake Updates[31305:4102377] [User Defaults] CFPrefsPlistSource<0x600002b80980> (Domain: ************, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): Transitioning into direct mode Is there a way to increase this limit? I need to store data.
2
0
923
Dec ’22
How To Declare Optional Parameter Function
I have a function like this @ViewBuilder   func addInfo(_ text: String, action: (() -> Void)?, addDivider: Bool = true, centerAlignment: Bool = false, isBold: Bool = false) -> some View {     VStack {       Text(text)         .fontWeight(isBold ? .bold : .regular)         .frame(maxWidth: .infinity, alignment: centerAlignment ? .center : .leading)         .padding([.leading, .trailing], 10)         .padding([.top, .bottom], 5)         .contentShape(Rectangle())         .onTapGesture {           if let action {             action()           }         }       if addDivider {         Divider()       }     }   } I do not understand why i get a compile error Expected type after '->' if i call the function like this addInfo("Sample", action: () -> Void {             }) The error points to Void. What is the correct way to do this? Please advise.
2
0
837
Dec ’22
Parser Json with Single Quote
Hi. I am having issues with json parsing. all my source data use double quote except for one. here is the sample do { let json = "[['16772', 'Cebu', 'Philippines']]" if let jsonArray = try JSONSerialization.jsonObject(with: Data(json.utf8), options: []) as? [[Any]] { print("Hello World") } } catch { print(error) } if the json string is let json = "[[\"16772\", \"Cebu\", \"Philippines\"]]" it works ok. but if it is single quote, then it gives out the error message Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 2." UserInfo={NSDebugDescription=Invalid value around line 1, column 2., NSJSONSerializationErrorIndex=2} What am i missing to enable parsing single quote normally? Thoughts?
2
0
1.9k
Dec ’22
How To Fix CoreData: error: Failed to load mode model named ...
Hi. I have no clue what I am doing wrong or am i missing something else. I keep getting the error message CoreData: error: Failed to load model named DMTideCity Please see attached image for data model. My goal is just to load this but I dont know why I keep getting that error message. struct TideDataController {       static let shared = TideDataController()   let cityContainer: NSPersistentContainer       init() {     print("init")     cityContainer = NSPersistentContainer(name: "DMTideCity")     print(cityContainer)     cityContainer.loadPersistentStores { description, error in       if let error {         print("Core Data Citys failed to load: \(error.localizedDescription)")       }       else {         print("Core Data Citys loaded")       }     }   } } In my view, i declare a variable like this let tideDataController = TideDataController.shared So it never reaches the print(cityContainer) because of that error message. Thoughts?
1
0
1.9k
Dec ’22
How To Set Values To Binding Variable
I have a model struct struct Temp { var cityUrlId: String {     get {       print(_cityUrlId)       print("gettting="+StringTool.nullToString(_cityUrlId).trim())              return _cityUrlId     }     set(newValue) {       print("newvalue="+newValue)       _cityUrlId = _cityUrlId       print("_cityUrlId="+_cityUrlId!)     }   } } The parent view has a state variable e.g. @State var temp: Temp and a child view as a new window with @Binding var temp: Temp My question is that when the temp in child view sets a value for cityUrlId property, it's ok. but once i set a new value in the parent view, the getter returns nil. why is that? is the solution for this have to be a class for Temp instead of a struct?
4
0
1.6k
Jan ’23
Why Doesnt this Wrap Correctly?
struct TideForecastInfoView: View {       var geometryProxy: GeometryProxy       var body: some View {     VStack {       getHeaders(geometryProxy)               TideForecastEntryView(geometryProxy: geometryProxy)           .padding(2)     }     .background(.white)     .clipShape(RoundedRectangle(cornerRadius: 14))     .shadow(radius: 8)   }       @ViewBuilder   func getHeaders(_ geometryProxy: GeometryProxy) -> some View {     HStack {       HStack {         Text("tide")           .frame(maxWidth: geometryProxy.size.width * 0.25)         Text("time")           .frame(maxWidth: geometryProxy.size.width * 0.5)         Text("height")           .frame(maxWidth: geometryProxy.size.width * 0.25)       }       .padding(8)     }     .frame(maxWidth: .infinity)     .background(.gray)   }   } struct TideForecastEntryView: View {       var geometryProxy: GeometryProxy       var body: some View {     HStack {       Text("High Tide")         .frame(maxWidth: geometryProxy.size.width * 0.25)       Text("1:08 AM (Tue 03) January")         .frame(maxWidth: geometryProxy.size.width * 0.5, alignment: .leading)       Text("1.31 m (4.3 ft)")         .frame(maxWidth: geometryProxy.size.width * 0.25)     }   } } Result looks like this 03 should be on the first line and maybe parts of the January word. is there something else missing in the Text view option that i need to declare? Also how to vertical align top for text High Tide. it is always vertically centered. I tried to set alignment: .top in the frame but doesnt do anything. Thoughts?
1
0
803
Jan ’23
How To Create Data Json Object from Empty String
This is what I tried to do. I am not sure what is wrong. anyone got ideas? let data: Data? = try? JSONSerialization.data(withJSONObject: "") and it says reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write' even if i put in "{}" error is the same. thoughts? Purpose for this is i want set this to a URLRequest.httpBody Thoughts?
1
0
1.2k
Jan ’23
Why Does Image Overlap In GridRow?
struct TweetFeedSelectionGridView: View {   private let ICON_SIZE: CGFloat = 40   private let ROW_BOTTOM_PADDING: CGFloat = 40       var body: some View {     Grid(alignment: .top, verticalSpacing: ROW_BOTTOM_PADDING) {       createTwitterFeedRow(["TwitterDilg", "TwitterDoh", "TwitterDole"])       createTwitterFeedRow(["TwitterDswd", "TwitterDepEd", "TwitterMmda"])       createTwitterFeedRow(["TwitterNdrmmc", "TwitterPagasa", "TwitterPcoo"])       createTwitterFeedRow(["TwitterPhivolcs", "TwitterPia", "TwitterPna"])       createTwitterFeedRow(["TwitterPnp", "TwitterRedCross", "TwitterTxtFire"])     }     .frame(maxWidth: .infinity)     .background(.red)   }       @ViewBuilder   func createTwitterFeedRow(_ feeds: [String]) -> some View {     GridRow {       createTwittedFeedCell(feeds[0])       createTwittedFeedCell(feeds[1])       createTwittedFeedCell(feeds[2])     }     .frame(maxWidth: .infinity)   }       @ViewBuilder   func createTwittedFeedCell(_ iconLabel: String) -> some View {     VStack {       Image(uiImage: UIImage(named: iconLabel)!)         .frame(width: ICON_SIZE, height: ICON_SIZE)       Text(iconLabel.replacingOccurrences(of: "Twitter", with: ""))         .padding(.top, 10)     }   } } struct TwitterFeedSelectionGridView_Previews: PreviewProvider {   static var previews: some View {     TweetFeedSelectionGridView()   } } Why does the image in the first row overlap? I have no clue why. The image is an ImageSet of 80, 160 and 240x240 images.
2
0
714
Jan ’23
Possible to set body view's background to transparent?
Please see screenshot. Currently the one in white has an animation in the middle. i wish to set the background of the body's view to transparent so that only the animation from my app is visible (it's like the home screen but only my animation is shown when the app is run. Is that possible? I tried to set VStack's background color opacity to 0 but nothing happpens. Or is it something else that needs to be modified? Thoughts?
1
0
724
Jan ’23
Deploy Release App To Device
I have a question regarding releasing an app to a device. I tried to release a debug app but I noticed that when i disconnect the cable from the device, the app cannot be run anymore. So instead, I have to transfer a release app to the device. However, there are some things I do not understand with regards to profiles. Do i have to create a provisioning profile just to be able to have my release built app installed in my iPhone? Or is there another way. Because while looking into this, I came to a conclusion that I have to have a developer account (which forces me to pay 100usd per year). And i have no plans to publish any app until I manage to finish 3 of them. I only plan to get a developer account once. all 3 are tried and tested in a real device. Thoughts?
0
0
530
Feb ’23
For Loop Conversion in Swift
Hi, i have only seen for loop samples that involve indexes or using for item in items. I come from a java background and i cannot seem to confirm if this can actually be converted to a swift for loop. thoughts? for (EdgeNode edge = aet.topNode ; (edge != null); edge = edge.next)
1
0
599
Feb ’23
How to set instance of a property of the same class type
See sample class class A { var proxy: A init () { proxy = self } } In Java, i could do something like this class A { A proxy; A () { proxy = this } } so when i instantiate A sample = new A(); the proxy variable will be set to the "this" keyword. But in Swift, the only related keyword to it is self but it does not behave the same way. It merely serves somewhat of a pointer to properties and methods that it belongs to it. Is this possible in Swift? if yes, how to go about this? I could not find any solution (perhaps because there is a term for that style? which I have no clue about) thoughts?
1
0
615
Feb ’23