vendredi 29 janvier 2021

How To Pre-Select CheckBox in SwiftUI

This is my CheckBoxField

How do I display a checkboxfield with a checkmark shows it was pre-checked already?

Here is how I use it. I would like to see the checkboxfield has a checkmark in there when loading like this one.

enter image description here

CheckboxField(
    id: "Completed",
    label: "Completed",
    callback: self.checkboxSelected
)

func checkboxSelected(id: String, isMarked: Bool) {
    print("This is done ->>> \(id) is marked: \(isMarked)")
}

import SwiftUI

struct CheckboxField: View {
    let id: String
    let label: String
    let size: CGFloat
    let color: Color
    let textSize: Int
    let callback: (String, Bool)->()
    
    init(
    id: String,
    label:String,
    size: CGFloat = 10,
    color: Color = Color.black.opacity(0.68),
    textSize: Int = 14,
    callback: @escaping (String, Bool)->()
    ) {
        self.id = id
        self.label = label
        self.size = size
        self.color = color
        self.textSize = textSize
        self.callback = callback
    }
    
    @State var isMarked:Bool = false
    
    var body: some View {
        Button(action:{
            self.isMarked.toggle()
            self.callback(self.id, self.isMarked)
        }) {
            HStack(alignment: .center, spacing: 10) {
                Image(systemName: self.isMarked ? "checkmark.square" : "square")
                .renderingMode(.original)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 20, height: 20)
                Text(label)
                .font(Font.system(size: size))
                .foregroundColor(Color.black.opacity(0.87))
                Spacer()
            }.foregroundColor(self.color)
        }
        .foregroundColor(Color.white)
    }
}



Aucun commentaire:

Enregistrer un commentaire