Post

Replies

Boosts

Views

Activity

Reply to Xcode Swift - How to ask the user display their pin from a UI button
I noted some errors in the following: you need to add the underscore before manager     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ The same for viewDidAppear:     override func viewDidAppear( _ animated: Bool) { I edited your code to format it without all the extra empty lines and used the code formatter (): import CoreLocation import MapKit import UIKit class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { @IBOutlet var mapView: MKMapView! let manager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear( _ animated: Bool) { super.viewDidAppear(animated) manager.desiredAccuracy = kCLLocationAccuracyBest manager.delegate = self manager.requestWhenInUseAuthorization() manager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ if let location = locations.first{ manager.stopUpdatingLocation() render(location: location) } } func render(location: CLLocation){ let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) let region = MKCoordinateRegion(center: coordinate, span: span) mapView.setRegion(region, animated: true) let pin = MKPointAnnotation() pin.coordinate = coordinate pin.title = "COVID-19 Case" pin.subtitle = "There is COVID-19 cases in your area. " mapView.addAnnotation(pin) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) - MKAnnotationView? { guard !(annotation is MKUserLocation) else { return nil } var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "custom") if annotationView == nil { //Create the view annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "custom") annotationView?.canShowCallout = true } else { annotationView?.annotation = annotation } annotationView?.image = UIImage(named: "viruscase") return annotationView } } To show / hide annotations, create an IBAction for the button and remove or add annotations. Create a var to keep status (are annotations visible). Here is an example from https://stackoverflow.com/questions/31266837/show-hide-annotation-when-button-is-pressed You'll have to adapt to your annotation set: only one annotation ? The simplest would be to keep annotation parameters in a property of the class and use it in addAttractionPins var annotationIsVisible = false @IBAction func showAnnotation(sender: AnyObject) { if !annotationIsVisible { addAttractionPins() annotationIsVisible = true }else { Map.removeAnnotations(Map.annotations) annotationIsVisible = false } } func addAttractionPins() { let filePath = NSBundle.mainBundle().pathForResource("Attractions", ofType: "plist") let attractions = NSArray(contentsOfFile: filePath!) for attraction in attractions! { let point = CGPointFromString(attraction["location"] as! String) let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y)) let title = attraction["name"] as! String let typeRawValue = (attraction["type"] as! String).toInt()! let type = AttractionType(rawValue: typeRawValue)! let subtitle = attraction["subtitle"] as! String let annotation = AttractionAnnotation(coordinate: coordinate, title: title, subtitle: subtitle, type: type) mapView.addAnnotation(annotation) } }
Topic: Programming Languages SubTopic: Swift Tags:
May ’21
Reply to onDrag conflicts with clicks on macOS
I tested and it works. I can drag (but that does not movve name in the list) I had just to set the window size to get multiple lines. struct ContentView: View { var items = ["Peter", "Mark", "Joe", "Frank", "Tim"] @State var selected: String? var body: some View { GeometryReader { geometry in NavigationView { List { ForEach(items, id: \.self) { item in NavigationLink(destination: Text(item), tag: item, selection: $selected, label: { Text(item) .onDrag { () - NSItemProvider in return NSItemProvider(object: String(item) as NSString) } }) } }.frame(width: geometry.size.width, height: geometry.size.height) } Text("") } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
May ’21
Reply to Sum of Multiple Stepper Functions with Label or Text Field
You should declare the steppers as IBOutlet collection      @IBOutlet var steppers: [UIStepper]! Take care of the order of declaration when you connect stepper to the IBOutlet. Do the same for labels.      @IBOutlet var labels: [UILabel]! Doing so, you can loop through steppers and add steppers[i].value or Double(labels[i].text) You can use reduce to do this: let total = labels.reduce(0.0) {sum, label in sum + (Double(label.text ?? "0") ?? 0.0) } labelTotal.text = String(Int(total))
Topic: Programming Languages SubTopic: Swift Tags:
May ’21
Reply to Swift UI Simulator Crash on Xcode
I don't understand how your code is supposed to work. How do you enter players ? And you just append empty names… And why do you initialise with an empty string and not just empty array ?   @State var pName: [String] = [] // [""] So I changed for: Button("next player") { playerEnterCount += 1 pName.append("\(playerEnterCount)") } I deleted names in the sheet, without crash (I could do it with blank names as well, and no crash either). I tested both in simulator and in Preview. Same result. So please explain your use case scenario.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
May ’21
Reply to Localization not loading in some cases
You could put it in viewWillAppear, to be sure it's done before any display. Is it a UITextView you localise ? If so, there is an old bug: UITextView text are not localized from Localizable.Strings with the text as key. Need to call with the item ID as (table is Main.strings):         helpTextView.text = NSLocalizedString("8Py-Vn-Jax.text", tableName: "Main", comment: "")   https://stackoverflow.com/questions/28596877/localization-of-ios-storyboard-uitextview-texts-are-not-localized
Topic: Programming Languages SubTopic: Swift Tags:
May ’21
Reply to Push data to other VC with protocol, error: force unwrapped a nil value
You don't show enough code to tell for sure. But writing this is very risky: func xyzzy() { phoneNumber = (phoneDelegate?.phoneNumber)! name = (nameDelegate?.name)! } Should write: func xyzzy() { phoneNumber = (phoneDelegate?.phoneNumber) ?? "" name = (nameDelegate?.name) ?? "" } Now to understand why: did VC1 and VC2 conform to the required protocol ? Could you show how you implemented protocol there ? How do you transition from VC1 / VC2 to VC3 ? If you segue, you need to set the delegate in destination (prepare in VC1 / VC2), such as: override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? VC3 {phoneDelegate = self } } Are VC1 and VC2 still existing when you call from VC3 ? That would be a serious reason for getting nil, if nameDelegate is nil Notes: if you segue, you don't really need protocols here. Setting a var in the destination directly in prepare should do it. See the complete logic for delegation here: https://forums.developer.apple.com/thread/111569 So please show complete code.
Topic: UI Frameworks SubTopic: UIKit Tags:
May ’21
Reply to Swift UI Simulator Crash on Xcode
When you perform ondelete, you need to decrement playerEnterCount. func delete(at offsets: IndexSet) { pName.remove(atOffsets: offsets) playerEnterCount -= 1 } At the end of the List, you have an empty name. So, you could filter the list : List { ForEach(pName.filter() {$0 != "" }, id: \.self) { aName in Text(aName) }.onDelete(perform: delete) }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
May ’21
Reply to Push data to other VC with protocol, error: force unwrapped a nil value
I already tried... phoneNumber = (phoneDelegate?.phoneNumber) ?? That doesn't work because it always takes the alternative data. That just proves phoneDelegate is nil. Could you show your complete code, that will be much easier. I guess you create in VC1 (and later in VC2) the destination VC (let's call them vc2 and vc3) in code: let vc2 = … // creating vc2 from VC1 then you present vc2. And do the same in VC2 to create vc3 If so, after creating vc3, set its delegate as needed: vc3.phoneDelegate = self vc3.nameDelegate = self In fact, you may have to go in 2 steps: nameDelegate set for vc2 (in VC1) and phoneDelegate set for vc3 in VC2. Then you would call vc3.phonedelegate?.phoneNumber and vc3.phonedelegate?.nameDelegate?.name But once again, please show code, there is too much to guess here. But there may be simpler ways to do it: create global var for phone and name, that you set in VC1 and VC2 and use in VC3. or carry over the vars: in VC2 declare var phoneNumber: String? After you instantiate vc2 in VC1, set the value vc2.phoneNumber = // the value you entered in VC1 in VC3, declare 2 var var phoneNumber: String? // yes, you redeclare here var name : String? After you instantiate vc3 (in VC2), set the value vc3.name = // the value you entered in VC2 and carryover the phoneNumber vc3.phoneNumber = self.phoneNumber // you carry over from VC2 to VC3
Topic: UI Frameworks SubTopic: UIKit Tags:
May ’21