Post

Replies

Boosts

Views

Activity

How To Make Optional Variables in SwiftUI View
Please see sample code struct Test: View { var array: [String] = [] init() { } var body: some View { Text(String(description: array.count) } } struct Test_Previews: PreviewProvider { static var previews: some View { Test(array: ["1", "2", "3"]) } } This one is a string array, I wish to pass some values only in preview because in the main view, i will be fetching data from a url. While setting this variable array to an empty array is the solution, what if my variable is a Struct? or Class? How will i make this optional and only supply a new Struct/Class instance in the preview only
2
0
994
Sep ’22
How To Open A New View From Popup Menu
This is my struct view for the overflow menu struct OverflowMenu: View {   var body: some View {     Menu {       NavigationLink(destination: SettingView()) {         Label{           Text("Settings")         }         icon: {           Awesome.Solid.cog.image             .foregroundColor(UIColor(hex: "#ffbd16"))         }       }     } label: {       Image(systemName: "ellipsis.circle")     }   } } Nothing happens when the button is clicked. The SettingsView is not shown in a new window. And the OverflowMenuView() is inside the NavigationView. Am i missing something else? var body: some View {     NavigationView { ..... HStack {                 Spacer()                 OverflowMenu()           } } }
3
31
819
Sep ’22
URLSession dataTask Does not fetch data
Hi, i had successfully fetched data from a URL but i cannot figure out why its sub link from the same domain, does not fetch any data. it always shows nil, but it contains byte like 39962 bytes. If it is nil, shouldnt that be something like 0 bytes Sample url is this. https://earthquake.phivolcs.dost.gov.ph/2022_Earthquake_Information/September/2022_0922_1059_B2.html This is how I fetch the data from url URLSession.shared.dataTask(with: URL(urlString)) { (data, response, error) in       guard let data = data else {         completion(nil)         return       }       if error != nil {         completion(nil)       }       else {         print(data)         completion(String(data: data, encoding: .utf8))       }     }.resume() Thoughts? What could be wrong? If it is https://earthquake.phivolcs.dost.gov.ph, i can fetch its data without issues.
4
0
1.3k
Sep ’22
Generic View Returning a Closure Option
Hi. I am new to SwiftUI and i am not sure what the right term for this is. Hoping someone can guide me Take this generic view for example (this one is incorrect since if i pass a view as parameter, how can it use the fetched data). struct FetchUrlContentView<Content: View>: View {   var url: String?   @State var loading = true   @State var error = false   @State var view: Content       var body: some View {     HStack {       if !NetworkTool.hasInternet() {         NoInternetView()       }       else if loading {         LoadingProgressView()       }       else if error {         SomethingWrongView()       }       else {         view       }     }     .task { if let urlLink = self.url {         fetchContentFromUrl(url: urlLink, { data in // Supposed to use data to the view here but it won't be generic. // any ideas?           self.loading = false         })       }       else {         self.loading = false         self.error = true       } } } What i am looking for is something of a way to keep on reusing FetchUrlContentView such that after data is fetched, i could call it like this FetchUrlContentView(url: "https://www.test.com/", loading: true) { data in MyView(data) } where MyView contains something like Text(data.description)
1
0
703
Sep ’22
Possible to have 2 let variables in 1 if condition?
I am converting Java code to Swift. This is the Java code try { if (filter == null || Float.parseFloat(ew.getMagnitude()) >= Float.parseFloat(filter)) liist.add(ew); } catch (NumberFormatException e) { } In Swift, currently this is what I have do {                     if let toFilter = filter, Float(ew.magnitude ?? "0") >= Float(toFilter ?? "0") {                           list.append(ew)                       }                     }                     else {                       list.append(ew)                     }                   } catch {                                        } Currently it even gives out an error that I have to add a ! after the Float() because "Force-unwrap using '!' to abort execution if the optional value contains 'nil'" But i do not want that, that is why I placed th do/catch there Please enlighten. Thank you
0
0
247
Sep ’22
Convert Date From Timezone
Hi, this is my function I cannot figure out why i always get jan 1, 2000 [time...] this is my code if let thisTime = Int64(time) {     let date = Date(timeIntervalSince1970: TimeInterval(thisTime) / 1000)     let dateWithTimezone = convertStringToDateWithTimezone(date)     print(formatDate(dateWithTimezone, "hh:mm a")!) } The date variable is correct but once I use convertStringToDateWithTimezone the result is always jan 1, 2000 [time...] Any idea what could be wrong?   func convertStringToDateWithTimezone(_ d: Date) -> Date {     let dateFormatter = DateFormatter()     dateFormatter.timeZone = TimeZone.current     return dateFormatter.date(from: (dateFormatter.string(from: d)))!   } func formatDate(_ date: Date?, _ pattern: String) -> String? {     if let date = date {       let dateFormatter = DateFormatter()       dateFormatter.locale = Locale(identifier: "en")       dateFormatter.dateFormat = pattern       return dateFormatter.string(from: date)     }     return nil   }
0
0
312
Sep ’22
What kind of string interpolation is this in Swift? {0} ...
So String interpolation is possible in Swift. However, the samples i have seen are either expressions or variables placed inside the "". Is it possible to replace with values if you have {0} and {1} in the string? I do not know what this is called in Swift if this is possible. I thought it is still interpolation but all I see are posts that do not have {0} ... Or is this feature not available in Swift?
1
0
514
Oct ’22
Why Main content and overflow menu button not clickable/scrollable?
Hi all, this is my last recourse by posting here since I really could not find a solution to my problem. My issue is that if there is a scrollable lazyVStack in the main content area, or if i cick on the overflow menu button, nothing happens. the button to show the side menu view works ok though. as is clicking on the rows of the LazyVStack. The cause of the ZStack top most but I am not sure what the problem is because the issue only occurs if it is in dark mode. And, the issue only happens if i am in dark mode. Just weird. This is the code var body: some View {     NavigationView {       ZStack(alignment: .leading) {         VStack(spacing: 0) {           HStack {             Button(action: {               withAnimation(.default) {                 show.toggle()               }             }) {               Image(systemName: "line.3.horizontal")             }             Spacer()             Text("Home")             Spacer()             OverflowMenu()           }           .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)         }         HStack {           SideMenuView(dark: $dark, show: $show, navigationManager: navigationManager)             .preferredColorScheme(dark ? .dark : .light)             .offset(x: self.show ? 0 : -UIScreen.main.bounds.width / 1.2)           Spacer(minLength: 0)           Rectangle().stroke(.clear).frame(width: show ? UIScreen.main.bounds.width - (UIScreen.main.bounds.width / 1.2) : 0)             .contentShape(Rectangle())             .onTapGesture {               if (show) {                 withAnimation(.default) {                   show.toggle()                 }               }             }         }         .background(Color.primary.opacity(self.show ? (self.dark ? 0.05 : 0.2) : 0).edgesIgnoringSafeArea(.all))       }       .navigationBarHidden(true)     }     .navigationViewStyle(.stack)   } OverflowMenuView struct OverflowMenu: View {       @State var isClickedSettings = false   @State var isClickedAbout = false   @State var isClickedFaq = false   @State var isClickedRemoveAds = false       var body: some View {     VStack {       NavigationLink(destination: SettingView(), isActive: $isClickedSettings) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedAbout) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedFaq) {         EmptyView()       }       .hidden()               NavigationLink(destination: SettingView(), isActive: $isClickedRemoveAds) {         EmptyView()       }       .hidden()               Menu {         Button {           isClickedSettings = true         }         label: {           Label {             Text(StringTool.localize("settings"))           }           icon: {             Awesome.Solid.cog.image               .foregroundColor(UIColor(named: "MenuSetting")!)           }         }                   Button {           isClickedAbout = true         }         label: {           Label {             Text(StringTool.localize("about"))           }           icon: {             Awesome.Solid.infoCircle.image               .foregroundColor(UIColor(named: "MenuAbout")!)           }         }                   Button {           isClickedFaq = true         }         label: {           Label{             Text(StringTool.localize("faq"))           }           icon: {             Awesome.Solid.bookOpen.image               .foregroundColor(UIColor(named: "MenuFaq")!)           }         }                   Button {           isClickedRemoveAds = true         }         label: {           Label{             Text(StringTool.localize("remove_ads"))           }           icon: {             Awesome.Solid.unlockAlt.image               .foregroundColor(UIColor(named: "MenuRemoveAds")!)           }         }       } label: {         Image(systemName: "ellipsis.circle")       }     }   } } Any Idea?
1
0
499
Oct ’22
How to disable cache in URLSession.shared.data in SwiftUI
All I have come across are NSURLSession. Is this possible for URLSession? How? I noticed my requests show up instantly so I figured these reponses are cached instead of fetching new ones. Caching should not be the default. Weird why it was set this way. Thoughts? This is my code. It is basic let url = URL(string: urlLink)! let (data, _) = try await URLSession.shared.data(from: url) print(String(decoding: data, as: UTF8.self))
1
0
3.4k
Oct ’22
How To Create a Marker With Callout in MapKit SwiftUI
I have not seen a tutorial that shows a callout when a marker is clicked in the map. Can anyone please confirm? Weird that this feature is not included. The callout I need is just a simple title and subtitle. That's all. Tutorials only show how to render using MapMarker, MapPin and custom MapAnnotations but these do nothing since they only show icons.
2
0
532
Oct ’22
What Happened to NSAttributedString in Swift 5? Bold Doesnt work?
The various posts showing NSAttributedString rendering html tags has become mute because the bold tag does not work anymore. Anyone know why? Or what the workaround is? I am using this as the extension in string (found this in stackoverflow)    var htmlAttributedString: NSAttributedString? {     do {       return try NSAttributedString(data: Data(utf8), options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)     } catch {       return nil     }   }       var htmlString: String {     return htmlAttributedString?.string ?? ""   } Bold just doesnt work. I do not see anything wrong with the code itself. It looks right. But it just does not render bold. I read about adding style tag in the string with the default apple system font in it hardcoded, tried that but didnt work out still.
1
0
757
Oct ’22
How To Zoom In Using northeast, southwest and center coordinate In Swiftui Map
I have the coordinate for northeast, southwest and center coordinates for a country Philippines but it does not zoom in there. This is the code I am using in OnAppear in the map view @State private var region = MKCoordinateRegion() var body: some View {     Map(coordinateRegion: $region)     .edgesIgnoringSafeArea(.all)     .onAppear() {       region = MapTool.getPARCoordinateRegion()     }   } static func getPARCoordinateRegion() -> MKCoordinateRegion {     let ph = getPHCountryPlaceMark()     let southWestPoint = MKMapPoint(x: ph.southWestLongitude, y: ph.southWestLatitude)     let northEastPoint = MKMapPoint(x: ph.northEastLongitude, y: ph.northEastLatitude)     let northWestPoint = MKMapPoint(x: southWestPoint.x, y: northEastPoint.y)     let mapRectWidth = northEastPoint.x - northWestPoint.x     let mapRectHeight = northWestPoint.y - southWestPoint.y     return MKCoordinateRegion(MKMapRect(x: southWestPoint.x, y: southWestPoint.y, width: mapRectWidth, height: mapRectHeight))   } static func getPHCountryPlaceMark() -> CountryPlaceMark {     let countryPlaceMark = CountryPlaceMark()     countryPlaceMark.longName = "Philippines"     countryPlaceMark.shortName = "PH"     countryPlaceMark.centerLatitude = 12.879721     countryPlaceMark.centerLongitude = 121.774017     countryPlaceMark.southWestLatitude = 4.613444     countryPlaceMark.southWestLongitude = 116.931557     countryPlaceMark.northEastLatitude = 19.574024     countryPlaceMark.northEastLongitude = 126.604384     return countryPlaceMark   } But instead zooms here. Thoughts?
1
0
627
Oct ’22
How To Change/Specify Custom View In Other areas Of the View for Every Child View Change In SwiftUI
Hi. Beginner here. Currently this is how my app looks like. What I wish to do is for every view that gets changed highlighted by the green square border, the menu item in the top horizontal HStack (my so called toolbar) also changes (highlighted in yellow circle). Currently, I use an ObservedObservable to change the view (green square) via the sidebarmenu. What is the best approach to the toolbar part? I was thinking that maybe within the child view e.g. SampleMap1, it has a custom menu item view variable which will be shown in the parent view (Where the yellow circle is lcoated) to add the menu item view. But I am not sure how to go about it. Advise, suggestions appreciated. Thoughts? These are what i have so far ... struct MainContent: View {   @ObservedObject var navigationManager : SidebarNavigationManager       var body: some View {     VStack(spacing: 0) {       switch navigationManager.menuCategory {         case .SAMPLE1:           SampleMap1()         case .SAMPLE2:           SampleMap2()       }     }     .navigationBarTitleDisplayMode(.inline)   } } And content view looks like this ... struct ContentView: View {   @StateObject var navigationManager = SidebarNavigationManager()    @State var show = false   var body: some View {     NavigationView {       ZStack(alignment: .leading) {         VStack(spacing: 0) {           HStack {             Button(action: {               withAnimation(.default) {                 show.toggle()               }             }) {               Image(systemName: "line.3.horizontal")             }             Spacer()             Text("Home")             Spacer() // This is where I wish to put like 2 or 3 menu items, default hidden and will show when the child view provides a menu item view with it that will get shown here             OverflowMenu() <-- ordinary view           }           .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)         }         HStack {           SideMenuView(show: $show, navigationManager: navigationManager)             .offset(x: self.show ? 0 : -UIScreen.main.bounds.width / 1.2)           Spacer(minLength: 0)           Rectangle().stroke(.clear).frame(width: show ? UIScreen.main.bounds.width - (UIScreen.main.bounds.width / 1.2) : 0)             .contentShape(Rectangle())             .onTapGesture {               if (show) {                 withAnimation(.default) {                   show.toggle()                 }               }             }         }       }       .navigationBarHidden(true)     }     .navigationViewStyle(.stack)   } } struct SampleText : View {   let text: String       var body: some View {     Text(text)   } }
1
0
476
Oct ’22
How To Declare A Variable of Type Function and Pass Function To it?
Is this possible? I have a class/struct that will store a function that will be used as an action to the button. e.g. struct Test { var action: (() -> Void)? } This works tempfunc() -> Void { print("clicked it") } let test = Test() test.action = tempfunc Button("click me", action: test.action) What I want to do is something like this. test.action = () -> Void { print("clicked") } Is this possible? If i try that code, error shows up saying "Cannot assign value of type '()' to type '() -> Void'"
1
0
542
Oct ’22