How I create textfield to select photo in swift?
How I create checkbox in swift ? <CODE>
How I create textfield to select photo in swift?
How I create checkbox in swift ? <CODE>
How I create textfield to select photo in swift?
You create a textField and in the modifier onChange, you select the photo in the perform closure.
.
How I create checkbox in swift ? <CODE>
Here is a code to create a CheckBox View in SwiftUI
struct CheckBox: View {
var label: String
var fontSize : Int = 16 // default value
@Binding var isOn: Bool
@Environment(\.colorScheme) var colorScheme
var boxOnLeft: Bool = true
var radioButton = false
var hilitedText = false
var completion : (() -> Void)? = nil // to handle radio buttons
var body: some View {
HStack {
if !boxOnLeft {
Text(label) //Texte à gauche, box à droite
.font(Font.custom("Helvetica Neue", size: CGFloat(fontSize)))
.fontWeight(hilitedText ? .bold : .regular)
}
if radioButton {
if isOn {
Text(colorScheme == .dark ? "🟢" : "🔵")
.frame(width: 20, height: 20)
.font(.system(size: 12))
} else {
Text(colorScheme == .dark ? "🔘" : "⚪️")
.frame(width: 20, height: 20)
.font(.system(size: 12))
}
} else { // Checkbox
if isOn {
Image(systemName: "checkmark")
.frame(width: 20, height: 20)
.border(.blue, width: 2)
} else {
Rectangle()
.frame(width: 20, height: 20)
.foregroundColor(.clear)
.border(colorScheme == .dark ? .white : .black, width: colorScheme == .dark ? 1 : 2)
}
}
if boxOnLeft {
Text(label) // Texte à droite, box à gauche (par défaut)
.font(Font.custom("Helvetica Neue", size: CGFloat(fontSize)))
.foregroundColor(hilitedText ? (colorScheme == .dark ? .green : .blue) : (colorScheme == .dark ? .white : .black))
.fontWeight(hilitedText ? .bold : .regular)
}
}
.onTapGesture {
isOn.toggle()
completion?()
}
}
}
You call it like this for Checkbox to have the square on right (ok is the state var to hold the status of checkBox)
CheckBox(label: "OK", isOn: $ok, boxOnLeft: false)
And to have label on right
CheckBox(label: "OK", isOn: $ok, boxOnLeft: true)
And for radioButtons (multiple buttons, ok is an array of Bool)
CheckBox(label: "OK",
isOn: $ok[item],
radioButton: true,
completion: {
for i in 0..<ok.count where i != item { // disable all others
ok[i] = false
}
}
})
You probably mean how to do that in SwiftUI, not UIKit/AppKit? Would you need this on iOS, macOS or a multiplatform implementation?
For checkbox, use Toggle
.
For selecting a photo, I would use perhaps a Button
or a Menu
to initiate the user interaction and then import PhotosUI
and use PHPickerViewController
. Unless you are selecting the photo from the file system, not from the Photos app.
On iOS and macOS you can also use the fileImporter View presentation modifier, if you wish to import an image file, instead of selecting a photo from the Photos app.