Post

Replies

Boosts

Views

Activity

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
512
Jan ’23
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.2k
Jan ’23
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.3k
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.5k
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
744
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
756
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
383
Dec ’22
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
360
Dec ’22
How Can WithAnimation Code be placed inside the view to be animated
Hi. My view gets animated with a call frmo a block of code withAnimation.{ } how can i place this inside the view so that the binding variable will be the one to trigger the animation. Same as how sheets work. THis is my sample view import SwiftUI struct GradientLegendView: View {       @Binding var isShowingLegend: Bool       var labels: [String]?   var colors: [Color]?   var width: Float   var height: Float   var viewRect = Rectangle()       var body: some View {     if isShowingLegend {       HStack {         VStack {           if let labels {             ForEach(labels, id:\.self) { label in               Text(label)                 .frame(maxWidth: .infinity, alignment: .leading)                 .font(.system(size: 14))                 .foregroundColor(.black)                 .backgroundStyle(.red)                 .padding(0)                               if label != labels.last {                 Spacer()               }             }           }         }         .frame(maxHeight: .infinity)         .padding(8)         Rectangle()           .foregroundColor(.clear)           .background(LinearGradient(gradient: Gradient(colors: colors ?? []), startPoint: .top, endPoint: .bottom))           .padding(8)           .frame(width: 30)       }       .frame(width: CGFloat(width), height: CGFloat(height))       .background(.white.opacity(0.7))       .cornerRadius(5)       .shadow(color: Color.gray.opacity(0.7), radius: 8, x: 0, y: 0)       .padding()       .transition(.move(edge: isShowingLegend ? .leading : .trailing))     }   } } struct GradientLegendView_Previews: PreviewProvider {       static var previews: some View {     GradientLegendView(       isShowingLegend: .constant(true),       labels: SampleData.createHeatmapLegendLabelArray(),       colors: SampleData.createHeatmapLegendColorArray(),       width: 120,       height: 200     )   } } struct Sample { static func createHeatmapLegendLabelArray() -> [String] {     return ["Great", "Major", "Strong", "Moderate", "Small"]   }        func createHeatmapLegendColorArray() -> [Color] {     return [.red, .purple, .orange, .green]   } } And i use it here and run the animation using withAnimation { } @State private var isShowingLegend = true var body: some View {     Text("Hey") .frame(maxWidth: .infinity, maxHeight: .infinity)     .edgesIgnoringSafeArea(.all)     .task {       setupMenuItems()     }     .overlay(       HStack {           GradientLegendView(             isShowingLegend: $isShowingLegend,             labels: SampleData.createHeatmapLegendLabelArray(),             colors: SampleData.createHeatmapLegendColorArray(),             width: 120,             height: 200)         Spacer()       },       alignment: .bottom     ) } Now, say i also have a button instead of Text("hey") where the action code is withAnimation(isShowingLegend ? .easeIn(duration: 0.5) : .easeOut(duration: 0.5)) {         isShowingLegend.toggle()       } Is it possible that this withAnimatoin be placed inslide GradientLegendView and will execute if the isShowingLegend value is change?
1
0
903
Dec ’22
Anyone Worked With AsyncView By Ralf Ebert, Doesnt Work In TabView
struct Test { var body: some View {     AsyncView(       operation: { try await getData("https://localhost") },       content: { json         Text("data retrieved")       }     )   } func getData(_ url: String) async throws -> String {     return try await getRequest(url)   } } static func getRequest(_ sourceData: String?, _ useWindowsChar1252: Bool = false) async throws -> String {     guard let sourceData else {       return ""     }           var request = URLRequest(url: URL(string: sourceData.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!)     request.httpMethod = "get"           let (data, _) = try await URLSession(configuration: .ephemeral).data(for: request)     return useWindowsChar1252 ?       String(data: data, encoding: .windowsCP1252)! :       String(decoding: data, as: UTF8.self)   } You can just have one tab item in the TabView and the http request keeps on looping. any idea? struct MyTabView: View {       var body: some View { TabView { Test()         .tabItem {           Label("test", systemImage: "leaf")         } } } } Trying to understand the cause. Because If I put the AsyncView, say inside a ZStack, it works ok. Thoughts?
0
0
361
Dec ’22
Why Can't I do var test: some View?
I want to have a property in a struct/class where it is of type custom View e.g. var view: some View? So many issues here, I ended up doing var view: AnyView? But i got stuck here because whenever I assign a value to this, the app crashes. saying Could not cast value of type '__NSCFNumber' (0x7fdcdf9c3480) to 'NSString' (0x1192bac50). This i do not understand view should be some view so it si neither number nor string. any idea why? also. if i do this var view: (some View)? it is ok. but when i set a value to that property it says Cannot assign value of type 'DailyCityReportView' to type 'some View' My goal is to pass a custom view to a property.
1
0
634
Dec ’22
Can A Property In An ObservableObject listen to Another Property? How?
Hi. this is my observable object final class ToolbarItemProperties: ObservableObject {   var visible = false   var disabled = false   var icon = "questionmark"   var action: () -> Void = { }   var opacity: Double = 1 } the opacity property value should either be 0.5 or 1 depending on the value of the property disabled. How to listen to it? The purpose for this is because if i set a button to disabled, it does not render any way to the user to let them know it is disabled. So i thought of changing the opacity instead, hence the opacity property. So if i do something like this item.disabled = true the opacity property value should become 0.5. if disabled is set to false, the opacity value will be 1.
5
0
1k
Dec ’22
Aspect Ratio Of Image is Whacked
Hi. I am using Kingfisher library to load images. My problem is that when i resize the width, the calculated height does not follow. the height of the image when displayed is still short. What could possibly be wrong in my code? import SwiftUI import Kingfisher struct MyView: View {       var geometryProxy: GeometryProxy       var body: some View {     HStack {       HStack {         KFImage.url(URL(string: "https://volcano.si.edu/gallery/photos/GVP-11076.jpg"))           .cancelOnDisappear(true)           .fade(duration: 0.25)           .resizable()           .scaledToFit()       }       .frame(maxWidth: geometryProxy.size.width * 0.4, maxHeight: getHeight(Float(geometryProxy.size.width) * 0.4, Float(geometryProxy.size.height), Float(geometryProxy.size.width)))       Text("Text 1 Label")         .frame(maxWidth: geometryProxy.size.width * 0.65, alignment: .topLeading)         .padding(.leading, 10)         .padding(.top, 3)       Image(systemName: "chevron.right")         .frame(maxWidth: geometryProxy.size.width * 0.05)         .padding(.leading, 0)     }     .contentShape(Rectangle())   }       private func getHeight(_ imageWidth: Float, _ imageHeight: Float, _ screenWidth: Float) -> CGFloat { //    let ratio = Float(placeholder!.size.height / placeholder!.size.width) //    print(ratio) //    print(ratio * width) //    print("______") //    return CGFloat(ratio * width)     let ratio = screenWidth / imageWidth     return CGFloat(imageHeight * ratio)   } } The Image should expand since i set the width of the image to at least 40% of the screen width. Or could my calculation for getting the height may be wrong? Thougts?
1
0
759
Dec ’22
How To Remove Extra Space Around Text
I have an image and text side by side in an HStack set to top alignment. I have no clue what this extra space is. The square shape and the text are not top aligned. I tried to set padding(0) to Text() to no avail. Any idea what this is? This is the code for the HStack. HStack(alignment: .top) {       Rectangle()         .fill(.red)         .frame(width: 15, height: 15)         .padding(.leading, 3)       Text("Heyasfd asdfsafds af awf s".uppercased())         .foregroundColor(.black)       Spacer()     } Thoughts?
1
0
3k
Dec ’22