Post

Replies

Boosts

Views

Activity

Reply to Picker View Data used elsewhere
With the present code:   let data = ["Aluminum 100", "Aluminum 80", "Aluminum 63", "Aluminum 50", "Steel 120", "Steel 100", "Steel 72"] when you test:     if data == ["Aluminum 100"]{ you test in fact:     if ["Aluminum 100", "Aluminum 80", "Aluminum 63", "Aluminum 50", "Steel 120", "Steel 100", "Steel 72"] == ["Aluminum 100"]{ So that is false. OOPer explained how to solve. Note that you can streamline your formulas: consumptionAir = (Double(plannedDepth.text!) + 33) / 33 * 1.4 But you need to make it more robust: if text is empty or nil, you'll crash let depthText = plannedDepth.text ?? "0" // Handle nil textField let value = depthText == "" ? 0.0 : (Double(depthText) ?? 0.0) // Handle empty textField: value is zero ; and if text is not a num (eg: "abcd", also zero consumptionAir = (value + 33) / 33 * 1.4 // No more risk of crash For timeOutput.text, you should at least show the unit and better convert to hours and minutes.
Topic: Programming Languages SubTopic: Swift Tags:
May ’21
Reply to Get data from JSON, only if it is in array
You need to append the element to the array. Replace self.purchases_new = items[position] // Cannot assign value of type 'WelcomeElement' to type '[WelcomeElement]' by self.purchases_new.append(items[position]) At line 9, if not connected, you should exit: print("Not connected") return After line 17, you should break: no need to continue searching (if I understood well your code). line 21: self.purchases_new = items That will crash the array you have just built. Why do you do this ? You can also simplify greatly your code by replacing: for position in 0...items.count-1 { for a in arrayInput { if a == items[position].name { purchases_new.append(items[position]) break } } } with purchases_new = items.filter() { arrayInput.contains($0.name)}
Topic: App & System Services SubTopic: Core OS Tags:
May ’21
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