Post

Replies

Boosts

Views

Activity

Why Is Bottom Sheet Full Screen? What is the workaround for Dynamic Height?
Hi. Beginner here. I am looking at bottom sheet and it is frustrating that the result is always full screen. Sure, in iPad it gets displayed as a modal dialog. I wonder why they just let it behave like that in the iPhone. The sheet should resize. based on the contents. What is your workaround for this? Should I still use sheet? or do it some other way using something else? I looked at .presentationDetents() but i can only set a fixed height to it. My content can be either 3,4,5,6,7... lines of Text() so my goal is to make the sheet height based on the contents inside it. Thoughts, ideas welcome.
2
0
2.2k
Oct ’22
Why Not Every Part Of View Is Clickable In NavigationLink
My navigation link looks like this struct ContentView: View { var body: some View {     NavigationView {       GeometryReader { geometryProxy in         NavigationLink {             EmptyView() // Any view         }         label: {           TestView(geometryProxy: geometryProxy)               .buttonStyle(.plain)                .padding(.leading, 8)         }         .buttonStyle(.plain)         .padding(.leading, 0)       }     }   } } And my test view looks like this struct TestView: View { var geometryProxy: GeometryProxy       var body: some View {     HStack {       Text("Some text here extra space on right")         .frame(maxWidth: geometryProxy.size.width * 0.85, alignment: .leading)       HStack {         Text("9.4")           .lineLimit(2)           .padding(8)       }       .frame(maxWidth: geometryProxy.size.width * 0.15)       .padding([.top, .bottom], 4)     }   } } Because there is some gap between the text "Some text here extra space on right" and "9.4", when that area gets tapped nothing happens. NavigationLink will only work when any text is tapped. Why is that? What is lacking here that will make any view in the TestView cllickable, including empty space.
2
0
1.1k
Oct ’22
Anybody Use SwiftClipper Here? Can't Instantiate A Class Without Init.
Hi. Beginner here. https://github.com/lhuanyu/SwiftClipper I am trying out Swift Clipper and when clipping arrays of CGPoint, I get the error message ClipperError(message: "Error: PolyTree struct is needed for open path clipping.") Problem is, I cannot instantiate PolyTree class because there is no init() inside of it. https://github.com/lhuanyu/SwiftClipper/blob/master/Sources/SwiftClipper/PolyNode.swift Does this mean it is best I copy the whole library source code to my project so I can at least add an init() so I can instantiate it? This is a simple method I am using to loop through each CGPoint array and union them. func cb(_ e: [[CGPoint]]) -> [CGPoint] {     var t: [CGPoint] = []     if !e.isEmpty && e.count > 1 {       t = e[0]       var paths = Paths()       let c = Clipper()       for o in (1..<e.count) {         do {           paths.removeAll()           c.clear()           c.addPath(t, .subject, false)           c.addPath(e[o], .subject, false)           try c.execute(clipType: .union, solution: &paths)           t = paths.first ?? []         } catch {           print(error)         }       }     }     return t   } Thoughts? Is this the only way to instantiate? By copying the source files to my project and add the init constructor there? Or, is there a hack to forcefully add an init constructor of a lib? (Though I do not think this is possible)
9
0
775
Oct ’22
Import An Objective-C Library To A Swift Project
All posts i came across instructs the user to import the objective c files into the swift project so that a bridging header file can be created to expose it. Does this mean i have to instead download the objective c library, extract and copy all the files to the swift project? where the prompt to create the bridging header will be triggered? Or is there a way to install the objective c library via cocoapods and manually trigger to create the bridging header to make it usable? I prefer the latter, if it is possible?
0
0
413
Oct ’22
LazyHGrid Equal Distribution
Wish to ask for suggestions. My goal is to have a view where user inputs an array of strings. Depending on the number of strings, should have equal distribution of spacing between them. E.g. 5 items. 1st item should be top, last item should be bottom while the 2nd-4th should be in between and all of them should have equal spacing. This is what I have import SwiftUI struct MyView: View {       @State private var labels: [String]? var labels = ["Great", "Major", "Strong", "Moderate", "Small"]  var colors = [.blue, .red]     HStack {       Spacer()       LazyHGrid(rows: [GridItem(.adaptive(minimum: 120))]) {         if let labels {           Group {             ForEach(labels, id:\.self) { label in               Text(label)             }           }         }       }       .frame(maxHeight: .infinity)       Rectangle()         .foregroundColor(.clear)         .background(LinearGradient(gradient: Gradient(colors: colors ?? []), startPoint: .top, endPoint: .bottom))       Spacer()     } } The result is not what I expected it to be. Notice the orange arrows. If i add more strings, ["Great", "Major", "Strong", "Moderate", "Small", "Great", "Major", "Strong", "Moderate", "Small"], it becomes 2 columns. Why is that? Maybe because the minimum value si 120? Is there a way to automatically have some formula where the minimum value is set based on the number of strings in the array?
1
0
467
Oct ’22
Why overlay is not on top
Please see image. I want the text "one case per million to extend". but in this scenario, it seems that the image overlay is occupying space inside the the view where the text are located Same as "One Death Per People". I think the first line should be "One Death Per" and maybe because the image is big that it somehow is occupying its area? (But i placed the image in overlay so it should be rendered no top) I think the word "Per" should still in in the first line. Any idea what could be the problem? This is my code struct Stat: View {       var body: some View {     VStack {       Text("One Case Per People")         .frame(maxWidth: .infinity, alignment: .leading)         .font(.system(size: 19))       Text("2")         .frame(maxWidth: .infinity, alignment: .leading)         .font(.system(size: 15))       Spacer()     }     .padding(8)     .frame(minHeight: 100)     .cornerRadius(8)     .background(Color.gray)     .overlay(       Image(systemName: "person.3.fill")         .resizable()         .frame(width: 60, height: 60, alignment: .trailing)         .padding(8),       alignment: .bottomTrailing     )   } } I used a grid to display them ScrollView {         LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {             Stat()             Stat()             Stat()             Stat()           }         }       } Thoughts?
4
0
1.5k
Oct ’22
Dictionary To Json Incorrect
Hi. this is my sample code import Foundation var features = [[String: Any]]() var geo = [String: Any]() geo["type"] = "FeatureCollection" geo["features"] = features let geoJson = try? JSONSerialization.data(withJSONObject: String(data: geo, encoding: .utf8)!, options: []) Why does the error message say Cannot convert value of type '[String : Any]' to expected argument type 'Data' I am going to use the data in the GMUGeoJSONParser(data: ...) in maps ios utils
1
0
443
Nov ’22
NavigationSplitView No Toggle Button
I went back to square one since the NavigationLink isActive is deprecated, this is when I found out about NavigationSplitView which removes the hassle of creating a 2 column app. However, I can never figure out why the toggle button does not show. I copied this sample code (already tried 2 tutorials, copy pasted them but still no toggle button) Anyone know why? import SwiftUI enum DemoScreen: String, Codable {   case first, second, third   var title: String {     rawValue.capitalized   } } struct ContentView: View {   @State   private var selection: DemoScreen? = .first   var body: some View {     NavigationSplitView {       sidebarContent     } detail: {       detailContent     }   } } extension ContentView {   var sidebarContent: some View {     List {       link(to: .first)       link(to: .second)       link(to: .third)     }   }   func link(to page: DemoScreen) -> some View {     NavigationLink(value: page) {       Text(page.title)     }   } } extension ContentView {   @ViewBuilder   var detailContent: some View {     if let selection = selection {       detailContent(for: selection)         .buttonStyle(.bordered)     } else {       Text("No selection")     }   }   @ViewBuilder   func detailContent(for screen: DemoScreen) -> some View {     switch screen {     case .first: Button("First button") {}     case .second: Button("Second button") {}     case .third: Button("Second button") {}     }   } } Why is there no toggle button above? And why is the menu always showing? I cant see the detiail view anymore
1
0
909
Nov ’22
Why is this URL nil?
I am testing this in playground. I have no clue why this url does not work? nil is returned. print(URL(string: "http://202.90.159.177/geoserver/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=true&LAYERS=Boundary:Boundary_Province&TILED=true&WIDTH=256&HEIGHT=256&CRS=EPSG:3857&STYLES&BBOX=%f,%f,%f,%f")) The cause is &BBOX=%f,%f,%f,%f but i do not understand why that full url doesnt work if that is included. Going to use this in GMSURLTileLayer in ios maps utils.
1
0
673
Nov ’22
"Invalid top-level type in JSON write"
I have seen posts about this error message but i am making a new one because my case is different. the json is valid. so i have no clue why it gives out this error. Sample json here i removed the forward slash so it will be clean since when i do a print() it always shows as "key": "value" this is the code i use to convert it to data then it gives out that error. i checked the json in online json validator sites and it's good. let string = the json string from the url above let jsonObject = try? JSONSerialization.data(withJSONObject: string, options: []) It is supposed to be a json array. any idea why the error?
2
0
3.1k
Nov ’22
How To Use Call A BInding Variable From A GMSMapViewDelegate Coordinator
Hi, asking this here because this is not about google maps ios sdk issue but regarding the use of binding. My map view currently looks simple. import SwiftUI import GoogleMaps import GoogleMapsUtils struct MapView: UIViewRepresentable {       var geoJsonParser: GMUGeoJSONParser?       func makeUIView(context: Self.Context) -> GMSMapView {     let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: GMSCameraPosition())     mapView.delegate = context.coordinator     return mapView   }       func updateUIView(_ mapView: GMSMapView, context: Context) {     mapView.clear()           if let geoJsonParser {       print(geoJsonParser.features)     }   }       func makeCoordinator() -> Coordinator {     Coordinator(owner: self)   }     } class Coordinator: NSObject, GMSMapViewDelegate {      let owner: MapView       init(owner: MapView) {     self.owner = owner   }       func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {     print("tapped at coordinate")     print(owner)   } } class Coordinator: NSObject, GMSMapViewDelegate {      let owner: MapView       init(owner: MapView) {     self.owner = owner   }       func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {     print("tapped at coordinate")     print(owner.geoJsonParser)   } } My question is when i tap on the map, the mapView didTapAtCoordinate gets called but the geoJsonParser variable is always nil. So I thought i would use Binding in this case since when the MapView struct is used, I pass a @State geoJsonParser to its parameter. My question is, from within the MapView struct, I am not sure what else I could be lacking so that print(owner.geoJsonParser) will not return nil I tried to set the variable to var geoJsonParser: Binding? = nil But after tapping on the map and the mapView didTapAtCoordinate is called, print(owner.geoJsonParser) returns an error Cannot convert value of type 'Binding<[any GMUGeometryContainer]>' to expected argument type '[any GMUGeometryContainer]' Same error message in the print statement in updateUIView(). Any idea what could be wrong here? My goal is to have owner.geoJsonFeature not be nil.
0
0
512
Nov ’22
Why does @Binding Force you To Declare it as Param?
A sample struct code struct Test { @Binding var name: String? } Why does it force me to have to instantiate it with Test(name: "blabla") Is there a way to not have to initialize this in the param? since It is an optional type. Binding<String?> works differently from @Binding, so ive read. Though one can do Binding<String?>? or is this the only possible way to do it?
0
0
378
Nov ’22
AttributeGraph: cycle detected through attribute In Sheet
Hi. I am not sure why i get the error message AttributeGraph: cycle detected through attribute but this does happen i noticed if i have a Text component render html. Here is the code import SwiftUI struct ContentView: View {   @State private var isShowingAlertSheet = false   @State private var alertTitle: String?   @State private var alertDescription: String?       var body: some View {     VStack {       Button(         "click me", action: {           alertTitle = "TITLE HERE"           alertDescription = "<b>hey</b>"           isShowingAlertSheet = true         }       )     }     .sheet(isPresented: $isShowingAlertSheet) {       DetailView(alertTitle: $alertTitle, alertDescription: $alertDescription)     }   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } struct DetailView: View {       @Binding var alertTitle: String?   @Binding var alertDescription: String?       var body: some View {     VStack {       Text(alertTitle ?? "")         .font(.system(size: 20))         .padding(.top, 10)         .padding(.bottom, 0)         .presentationDetents([.height(250)])       Text(fixTextSize(alertDescription?.htmlMutableAttributedString))         .frame(maxWidth: .infinity)         .padding(.top, 10)       Spacer()     }     .padding()   }       func fixTextSize(_ mutableAttributedString: NSMutableAttributedString?) -> AttributedString {     if let mutableAttributedString {       mutableAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, mutableAttributedString.length))       return AttributedString(mutableAttributedString)     }     return AttributedString()   } } extension String {   var htmlMutableAttributedString: NSMutableAttributedString? {     if let attributedString = try? NSMutableAttributedString(data: Data(self.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {       attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(.black), range: NSMakeRange(0, attributedString.length))       return attributedString     }     return nil   } } Thoughts?
0
0
1.5k
Nov ’22
Why Does Method Force Me To Add Mutating
Regardless if I use a protocol or not that contains this method, e.g. I have this var test: String? func setupData() -> Void { test = "New value" } Why does it say Cannot assign to property: 'self' is immutable" So if i add mutable to setupData() which becomes "mutating func setupData() { ... }", then i get another error message Cannot use mutating member on immutable value: 'self' is immutable I call setupData in onAppear() instead of init() for now. Putting it in init forces me to initialize the variables (sucks) I am lost on this one. Advise? This is used inside a Struct View. not a class.
1
0
1.7k
Nov ’22
LocationManager Error when requesting location
Hi . I am following the simple example from hacking with swift website. It is to request a location. import CoreLocation import CoreLocationUI class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {   let manager = CLLocationManager()   @Published var location: CLLocationCoordinate2D?   override init() {     super.init()     manager.delegate = self   }   func requestLocation() {     manager.requestLocation()   }   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {     print("hehe")     location = locations.first?.coordinate   } } In the view. I have some custom button that when clicked, will call locationManager.requestLocation() but it gives this error message Updates[14291:194102] *** Assertion failure in -[CLLocationManager requestLocation], CLLocationManager.m:1339 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didFailWithError:' *** First throw call stack: ( 0  CoreFoundation           0x0000000111b3a8cb __exceptionPreprocess + 242 1  libobjc.A.dylib           0x000000010d4efba3 objc_exception_throw + 48 2  Foundation             0x0000000116b3837c _userInfoForFileAndLine + 0 3  CoreLocation            0x000000010c1baf65 CLClientStopVehicleHeadingUpdates + 52782 7  SwiftUI               0x0000000113c6f5dc __swift_memcpy160_4 + 113486 8  SwiftUI               0x0000000113c6fe8d __swift_memcpy160_4 + 115711 9  SwiftUI               0x0000000113c6fdff __swift_memcpy160_4 + 115569 10 SwiftUI               0x00000001140a4270 objectdestroy.142Tm + 41347 11 SwiftUI               0x00000001140a4284 objectdestroy.142Tm + 41367 12 SwiftUI               0x00000001140a4270 objectdestroy.142Tm + 41347 13 SwiftUI               0x0000000113dba491 block_destroy_helper + 36990 14 SwiftUI               0x0000000113db9df2 block_destroy_helper + 35295 15 SwiftUI               0x0000000113f4b7a5 _callVisitToolbarContentType2 + 4011 16 SwiftUI               0x00000001146fa7c8 _callVisitStyleContextType2 + 11258 17 SwiftUI               0x00000001146f8e5e _callVisitStyleContextType2 + 4752 18 SwiftUI               0x00000001146f8f42 _callVisitStyleContextType2 + 4980 19 SwiftUI               0x00000001146f8720 _callVisitStyleContextType2 + 2898 20 UIKitCore              0x0000000120b384b9 -[UIGestureRecognizer _componentsEnded:withEvent:] + 153 21 UIKitCore              0x00000001211d7ebd -[UITouchesEvent _sendEventToGestureRecognizer:] + 662 22 UIKitCore              0x0000000120b286f7 -[UIGestureEnvironment _updateForEvent:window:] + 469 23 UIKitCore              0x000000012117aedb -[UIWindow sendEvent:] + 5282 24 UIKitCore              0x000000012114e7f2 -[UIApplication sendEvent:] + 898 25 UIKitCore              0x00000001211f5e61 __dispatchPreprocessedEventFromEventQueue + 9381 26 UIKitCore              0x00000001211f8569 __processEventQueue + 8334 27 UIKitCore              0x00000001211ee8a1 __eventFetcherSourceCallback + 272 28 CoreFoundation           0x0000000111a9a035 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 29 CoreFoundation           0x0000000111a99f74 __CFRunLoopDoSource0 + 157 30 CoreFoundation           0x0000000111a997d1 __CFRunLoopDoSources0 + 308 31 CoreFoundation           0x0000000111a93e73 __CFRunLoopRun + 927 32 CoreFoundation           0x0000000111a936f7 CFRunLoopRunSpecific + 560 33 GraphicsServices          0x000000011985b28a GSEventRunModal + 139 34 UIKitCore              0x000000012112d62b -[UIApplication _run] + 994 35 UIKitCore              0x0000000121132547 UIApplicationMain + 123 36 SwiftUI               0x00000001146b2cfb __swift_memcpy93_8 + 10826 37 SwiftUI               0x00000001146b2ba8 __swift_memcpy93_8 + 10487 38 SwiftUI               0x0000000113d68b7d __swift_memcpy195_8 + 12271 41 dyld                0x000000010be3d2bf start_sim + 10 42 ???                 0x0000000203a3d310 0x0 + 8651002640 ) libc++abi: terminating with uncaught exception of type NSException Message from debugger: Terminated due to signal 6 I really have no clue what is going on. It does not enter some breakpoint, it just crashes. Anything I am missing? Also, i could not find anything in the LocationManager regarding a callback when the location is retrieved? or it is a manual workaround that has to be done for this case? the issue may be because i need to include the function func locationManager( _ manager: CLLocationManager, didFailWithError error: Error ) but adds another question. Why do i get Error Domain=kCLErrorDomain Code=1 "(null)"
3
1
2.4k
Nov ’22