skip to Main Content

In SwiftUI, I have two textfields. One of them is String and the other should be Int. And I want textfields to appear empty before and after "save" functionality.

this is how I declare my Int variable

@State private var newItemDays: Int?

this is the textfields

TextField("Task Title", text: $newItemTitle)
                        .padding()
                        .background(Color.white)
                    
TextField("Days to Countdown", value: $newItemDays, formatter: NumberFormatter())
                        .keyboardType(.numberPad)
                        .padding()
                        .background(Color.white)

And my Ok button saves them.

 Button("OK") {
                            if let days = newItemDays {
                                
                                let newItem = CountdownItem(title: newItemTitle, daysLeft: days)
                                self.store.add(item: newItem)
                                newItemTitle = ""
                                newItemDays = 0
                                isTextFieldVisible = false
                            }
                            
                        }

If statement always return false even though I put integer there. If I remove optional from the declaration and make it equal to 0, it works but this time I see 0 at the textfields (it should appear empty)

Any help?

2

Answers


  1. You can create a custom NumberFormatter & set the zeroSymbol to be an empty String:

    let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.zeroSymbol = ""
        return formatter
    }()
    

    And your TextField becomes:

    TextField("Days to Countdown", value: $newItemDays, formatter: formatter)
    
    Login or Signup to reply.
  2. Use format: instead of formatter:

    TextField("Days to Countdown", value: $newItemDays, format: .number)
    

    When value is Int? it will appear empty initially.

    By the way, you shouldn’t init objects like NumberFormatter() inside body it is a memory leak, best stick to value types.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search