I am trying to get integer input by using textfield. However, I noticed that if I changed the binding variable as optional with an initial value of null, the textfield would not work. I would like to keep it as null initially because I want the placeholder to show text before the input, and if the int variable starts with any valid value, the text would not be shown. Is there a way to fix things here?
struct TextFieldNumberInputView: View {
@Binding var intVariable: Int?
@State var isEditing: Bool = false
@State var placeholderText: String
@State var number: Int = 0
var body: some View {
VStack(alignment: .leading, spacing: 2){
TextField(placeholderText, value: $number, formatter: NumberFormatter()){
}
.textFieldStyle(InputTextFieldStyle())
.keyboardType(.numberPad)
.onReceive(Just(number)) {_ in
print("number pad being editing")
if isEditing == false && intVariable != nil {
isEditing = true
print("number is being edited")
} else if isEditing == true && intVariable != nil{
isEditing = false
}
}
Text(placeholderText)
.font(.caption2)
.foregroundColor(isEditing ? Color(.systemGray3):Color.clear)
.padding(.horizontal)
.padding(.horizontal, 12)
}.onTapGesture {
print("number pad being tapped, intVariable \(intVariable), \(number)")
if number != nil {
print("checking number")
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
}
}
}
}