I have a requirement of Checkbox (✅ as in to-do list) with textfield. Currently I have created button object like below :
Button(action: {
// do when checked / unchecked
//...
}) {
HStack(alignment: .top, spacing: 10) {
Rectangle()
.fill(Color.white)
.frame(width:20, height:20, alignment: .center)
.cornerRadius(5)
Text("Todo item 1")
}
}
I need to preserve checked
and unchecked
state in SwiftUI.
A checkbox is a standard User Interface element in the Apple world. As such, you would expect SwiftUI to have a Checkbox View element. But that is not the case. As of 2020, there is no some thing as a Checkbox View in SwiftUI.
Figure 1. Hello world again! Text in SwiftUI is a non-editable and read-only, that is used for presenting information on the screen. This tutorial is part of my SwiftUI Tutorial series.
To make text bold, use the following line. Line spacing lets you change the amount of space between lines of text. You can set a limit to the amount of lines Text can take up. It’s also possible to use custom fonts in SwiftUI. I like to do this through an extension like so. Then you can just use the font like any other.
This is an individual component and I used a callback method to get informed when the checkbox is selected or not. Step 1: Create a customizable and reusable checkbox view Step 2: Let use the component in the main view Use the checkboxSelected () callback function to know which checkbox is selected or not.
Here is a simple, re-usable checkmark component I created that follows a color scheme similar to other checkmarks on iOS (e.g. selecting messages in the Messages app):
import SwiftUI
struct CheckBoxView: View {
@Binding var checked: Bool
var body: some View {
Image(systemName: checked ? "checkmark.square.fill" : "square")
.foregroundColor(checked ? Color(UIColor.systemBlue) : Color.secondary)
.onTapGesture {
self.checked.toggle()
}
}
}
struct CheckBoxView_Previews: PreviewProvider {
struct CheckBoxViewHolder: View {
@State var checked = false
var body: some View {
CheckBoxView(checked: $checked)
}
}
static var previews: some View {
CheckBoxViewHolder()
}
}
You can use it in other views like this:
...
@State private var checked = true
...
HStack {
CheckBoxView(checked: $checked)
Spacer()
Text("Element that requires checkmark!")
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With