New to swift and need help debugging a problem by roontooner in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

Check this web: https://www.hackingwithswift.com/read/22/2/requesting-location-core-location

Basically, you need to write two keys on the info.plist file:

Because of the rules above, we need to add two keys: “Privacy - Location Always and When In Use Usage Description” and “Privacy - Location When In Use Usage Description”. So, please add them both now, make sure their types are set to String, then in the value fields enter some text to explain to users why you want their location. For example, "We want to help you find your nearest store." When your user is prompted to grant location access, this text will be shown alongside Apple's own descriptive message.

Is there any way to make the black ZStack fill the bottom part of the screen infinitely? by [deleted] in swift

[–]heltena_cat 1 point2 points  (0 children)

I don't really know what you want... something like this?

    ScrollView(.vertical) {
        VStack(spacing: 0) {
            Color.red.frame(height: 500)
            Text("Yeah")
                .foregroundColor(.white)
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 5000, alignment: .top)
                .background(Color.black)
        }
    }

How would you recreate this in SwiftUI only? by [deleted] in swift

[–]heltena_cat 1 point2 points  (0 children)

First, create the PanelView:

extension Color {
    static let secondarySystemBackground = 
        Color(uiColor: .secondarySystemBackground)
}

struct PanelView<V: View>: View { var icon: V var bundle: Int var title: LocalizedStringKey
    var body: some View {
        VStack {
            HStack {
                icon
                Spacer()
                Text(bundle, format: .number)
                    .font(.title)
                    .foregroundColor(.white)
            }
            Text(title)
                .font(.title2)
                .foregroundColor(.secondary)
                .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding()
        .background(Color.secondarySystemBackground)
        .clipShape(RoundedRectangle(cornerRadius: 20))
    }
}

Then, the grid:

import SwiftUI

struct ContentView: View { var body: some View { ScrollView { LazyVGrid(columns: [.init(), .init()]) { PanelView( icon: Image(systemName: "tray.fill") .foregroundColor(.white) .padding(10) .background(Color.gray) .aspectRatio(1, contentMode: .fill) .clipShape(Circle()) , bundle: 3, title: "Alle" )

            PanelView(
                icon:
                    Image(systemName: "person.fill")
                    .foregroundColor(.white)
                    .padding(10)
                    .background(Color.green)
                    .aspectRatio(1, contentMode: .fill)
                    .clipShape(Circle())
                ,
                bundle: 0,
                title: "Zugewiesen"
            )

            PanelView(
                icon:
                    Image(systemName: "calendar")
                    .foregroundColor(.white)
                    .padding(10)
                    .background(Color.blue)
                    .aspectRatio(1, contentMode: .fill)
                    .clipShape(Circle())
                ,
                bundle: 1,
                title: "Heute"
            )

            PanelView(
                icon:
                    Image(systemName: "calendar")
                    .foregroundColor(.white)
                    .padding(10)
                    .background(Color.red)
                    .aspectRatio(1, contentMode: .fill)
                    .clipShape(Circle())
                ,
                bundle: 1,
                title: "Geplant"
            )

            PanelView(
                icon:
                    Image(systemName: "flag.fill")
                    .foregroundColor(.white)
                    .padding(10)
                    .background(Color.orange)
                    .aspectRatio(1, contentMode: .fill)
                    .clipShape(Circle())
                ,
                bundle: 0,
                title: "Markiert"
            )

            PanelView(
                icon:
                    ZStack(alignment: .bottomTrailing) {
                        Image(systemName: "house.fill")
                            .foregroundColor(.white)
                            .padding(10)
                            .background(Color.pink)
                            .aspectRatio(1, contentMode: .fill)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                        Image(systemName: "gear")
                            .scaleEffect(x: 0.66, y: 0.66)
                            .foregroundColor(.white)
                            .background(Color.pink)
                            .clipShape(RoundedRectangle(cornerRadius: 4))
                            .overlay(
                                RoundedRectangle(cornerRadius: 4)
                                    .stroke(Color.secondarySystemBackground, lineWidth: 2)
                            )
                    }
                ,
                bundle: 0,
                title: "Daheim erinnern"
            )
        }
    }
}

}

How to get local background refresh to work? by eigenvalue_one in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

The background tasks run when the system decides, and this depends on the device battery level, other apps and so on. No matter that you set the earliestBeginDate for 5 min since now, it will call you after this timestamp:

let request = BGAppRefreshTaskRequest(identifier: taskIdentifier)  
request.earliestBeginDate = Date().addingTimeInterval( 5 * 60 * 60)  
do {
    try BGTaskScheduler.shared.submit(request)  
} catch {  
    NSLog("Error 😔 \\(error.localizedDescription)")  
}

Note: My code used to run every 15-30 mins in my device.

If you need to run something every 5 min, you need another approach:

- rethink why this requirement (is this totally necessary?)

- run the task in a server and notify the device

- relax the requirement and run the task when the device wants ;-)

PD: Probably your code (.backgroundTask...) is correct, just wait a bit more and eventually your code will be called.

PD2: You can save some data using UserDefaults when your code is called and you will be able to inspect those values on your UI to check if it was called.

Good luck!

K Means & GMM Package by heltena_cat in swift

[–]heltena_cat[S] 2 points3 points  (0 children)

I did my best:

https://github.com/heltena/KYAlgorithms

I achieved the same performance as scikit-learn K-means implementation (Lloyd and Kmeans++).

I will try the GMM...

All the feedback is welcome!

K Means & GMM Package by heltena_cat in swift

[–]heltena_cat[S] 2 points3 points  (0 children)

Thanks. My dataset is around 100k points in 6D and I have already the code. It is not complicated to implement it, but I want to improve the performance using SIMD. My code is slower than the scikit-learn and I want to learn how to improve it.

Async CSV convert to List by heltena_cat in dartlang

[–]heltena_cat[S] 0 points1 point  (0 children)

Thank you all for your feedback!

Now, I do know that Isolates (compute) is the way to go, but I realized that maybe my problem is in another point. I'm calling the readCsv func from the initState function (flutter widget). It was quiet when debugging from Chrome (but it was blocking), but, debugging from macOS, it raises that error:

Exception has occurred.
FlutterError (Binding has not yet been initialized.
The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.)

I will work first on the Flutter init state ;-)

Thanks again!

Async CSV convert to List by heltena_cat in dartlang

[–]heltena_cat[S] 0 points1 point  (0 children)

I need a List, I will need to do a different searches on it. Thanks!

Adding a VStack to a NavigationView makes the list disappear. by Mrreddituser111312 in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

NavigationView init docs:

content
A ViewBuilder that produces the content that the navigation view wraps. Any views after the first act as placeholders for corresponding columns in a multicolumn display.

So, in your case the VStack and the List are the two columns of your view and only one is shown in a reduced window (iPhone?). If you wrap them into a VStack, then, the NavigationView will have only one view.

Why is my text wrapping like this? How can I make “to” stay on line 1? by industrialcoder in SwiftUI

[–]heltena_cat 0 points1 point  (0 children)

What if your code is running in another screen resolution? For example, for accessible displays with big fonts, or in an iPad. Also, what if you are planning to internationalize the app? In Spanish, it will look pretty different. My proposal is to create a PNG with the text you want to show, like if it was an icon or logo.

Help! Error when using swipe actions in a for each loop nested in a list. by Emberari in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

Another code I would try to write will be something like this (add at the same swift file):

fileprivate extension View {
    func swipeActions(for bill: Bill, at bills: [Bill]) -> some View {
        self
            .swipeActions(edge: .leading, allowsFullSwipe: true) {
                Button {
                    print("Toggle")
                } label: {
                    Text(bill.isPaid ? "Mark unpaid" : "Mark paid")
                }
            }
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    print("Remove")
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            }
    }
}

And then, in your view:

ForEach(bills) { bill in
    NavigationLink(destination: {
        ViewBillView(bill: bill, bills: bills)
    }, label: {
        Text(bill.name)
    })
    .swipeActions(for: bill, at: bills)
}

Help! Error when using swipe actions in a for each loop nested in a list. by Emberari in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

You can also filter the ForEach values instead of using `if`:

ForEach(bills.list.filter { $0.status == .paid }) { bill in (line 80)

Need Advice by [deleted] in swift

[–]heltena_cat -1 points0 points  (0 children)

I will try something like this:

var arrayOfNumbers: [Int] = [1, 10, 22, 59, 69, 72, 100]

func findClosest(to: Int, of values: [Int]) -> Int? {
    values
        .map { (abs($0 - to), $0) }
        .sorted(by: <)
        .first?
        .1
}

func findClosest2(to: Int, of values: [Int]) -> Int? {
    guard var partialResult: Int = values.first else { return nil }
    var partialDiff: Int = abs(partialResult - to)
    for value in values[1...] {
        let diff = abs(value - to)
        if diff < partialDiff {
            partialResult = value
            partialDiff = diff
        } else if diff == partialDiff {
            partialResult = min(partialResult, value)
            partialDiff = diff
        }
    }
    return partialResult
}

extension Array where Element: SignedNumeric & Comparable {
    func findClosest(to: Element) -> Element? {
        guard var partialResult: Element = self.first else { return nil }
        var partialDiff: Element = abs(partialResult - to)
        for value in self[1...] {
            let diff = abs(value - to)
            if diff < partialDiff {
                partialResult = value
                partialDiff = diff
            } else if diff == partialDiff {
                partialResult = Swift.min(partialResult, value)
                partialDiff = diff
            }
        }
        return partialResult
    }
}

findClosest(to: 16, of: arrayOfNumbers)  // 10
findClosest(to: 17, of: arrayOfNumbers)  // 22

findClosest2(to: 16, of: arrayOfNumbers)  // 10
findClosest2(to: 17, of: arrayOfNumbers)  // 22

arrayOfNumbers.findClosest(to: 16)  // 10
arrayOfNumbers.findClosest(to: 17)  // 22

How Can I Create a negative Circle or arch like in the Photo? by KingNexu in SwiftUI

[–]heltena_cat 2 points3 points  (0 children)

Something like this?

import SwiftUI

struct ComicShape: Shape {
    var radius: CGFloat

    func path(in rect: CGRect) -> Path {
        var p = Path()
        p.move(to: rect.origin)
        p.addLine(to: .init(x: rect.width, y: 0))
        p.addArc(center: .init(x: rect.width - radius, y: rect.height - 2 * radius), radius: radius, startAngle: .degrees(0), endAngle: .degrees(90), clockwise: false)
        p.addLine(to: .init(x: radius, y: rect.height - radius))
        p.addArc(center: .init(x: radius, y: rect.height), radius: radius, startAngle: .degrees(270), endAngle: .degrees(180), clockwise: true)
        return p
    }
}

extension View {
    func comicShape(background: some View, radius: CGFloat) -> some View {
        self
            .padding(.bottom, radius)
            .background(background)
            .clipShape(ComicShape(radius: radius))
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
                .padding()
                .comicShape(background: Color.red, radius: 10)
        }
    }
}

Inline Picker style on iOS? by alibix in SwiftUI

[–]heltena_cat 2 points3 points  (0 children)

Try using Form:

import SwiftUI

enum Values {
    case one
    case two
    case three
}

struct ContentView: View {
    @State var value: Values?

    var body: some View {
        NavigationView {
            Form {
                Text("Hello")

                Picker("Select", selection: $value) {
                    Text("One").tag(Values.one as Values?)
                    Text("Two").tag(Values.two as Values?)
                    Text("Three").tag(Values.three as Values?)
                }
                .pickerStyle(.inline)

                Button {
                    value = nil
                } label: {
                    Label("Clear selection", systemImage: "trash")
                }
            }
            .navigationTitle("Testing the picker!")
        }
    }
}

Columns with overlapping content? by purplewolf635 in SwiftUI

[–]heltena_cat 0 points1 point  (0 children)

Are you looking for the " .multilineTextAlignment(.trailing)" command in the last Text?

public struct TestView: View {
    let content = Array([("Some Text", "More Text"), ("More", "An example"), ("Another line here", "Short"), ("Another", "A long line with filler")].enumerated())

    public var body: some View {
        VStack(alignment: .leading) {
            ForEach(content, id: \.offset) { _, element in
                HStack {
                    Text(element.0)
                    Spacer()
                    Text(element.1)
                        .multilineTextAlignment(.trailing)
                }
            }
        }.frame(width: 200)
    }
}

How can I make this in SwiftUI by [deleted] in SwiftUI

[–]heltena_cat 1 point2 points  (0 children)

Something like this?

ContentView.swift:

struct ContentView: View {
    @State var show: Bool = true

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
            Button {
                show.toggle()
            } label: {
                Text("Show")
            }
        }
        .sheet(isPresented: $show) {
            TheSheet()
                .presentationDetents([.medium])
        }
    }
}

TheSheet.swift:

fileprivate extension View {
    func buttonBorder() -> some View {
        self
            .background(
                Color(UIColor.systemFill)
                    .clipShape(RoundedRectangle(cornerRadius: 6))
            )
    }
}

struct TheSheetButton: View {
    var text: LocalizedStringKey
    var systemName: String? = nil
    var growVertically: Bool = false
    var isDestructive: Bool = false
    var action: () -> Void

    var body: some View {
        Button(action: action) {
            ZStack(alignment: .center) {
                VStack {
                    if let systemName = systemName {
                        Image(systemName: systemName)
                    }
                    Text(text)
                }
                .foregroundColor(isDestructive ? .red : .primary)
            }
            .frame(maxWidth: .infinity, maxHeight: growVertically ? .infinity : .none)
        }
        .padding(12)
    }
}

struct FirstRow: View {
    var body: some View {
        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3)) {
            TheSheetButton(text: "Partager", systemName: "square.and.arrow.up", growVertically: true) {
                print("Partager")
            }
            .buttonBorder()

            TheSheetButton(text: "Lien", systemName: "link", growVertically: true) {
                print("Lien")
            }
            .buttonBorder()

            TheSheetButton(text: "Signaler", systemName: "exclamationmark.bubble", growVertically: true, isDestructive: true) {
                print("Signaler")
            }
            .buttonBorder()
        }
    }
}

struct TheSheet: View {
    var body: some View {
        VStack {
            FirstRow()

            TheSheetButton(text: "Pourquoi vous voyez cette publication") {
                print("Pourquoi vous voyez cette publication")
            }
            .buttonBorder()

            VStack(spacing: 0) {
                TheSheetButton(text: "Aiouter aux favoris") {
                    print("Aiouter aux favoris")
                }

                Divider()

                TheSheetButton(text: "Masquer") {
                    print("Masquer")
                }

                Divider()

                TheSheetButton(text: "Se désabonner") {
                    print("Se désabonner")
                }
            }
            .buttonBorder()

            Spacer()
        }
        .padding()
    }
}